import { zodResolver } from '@hookform/resolvers/zod'; import { BeerStyle } from '@prisma/client'; import router from 'next/router'; import { FunctionComponent } from 'react'; import { useForm, SubmitHandler, FieldError } from 'react-hook-form'; import { z } from 'zod'; import BreweryPostQueryResult from '@/services/BreweryPost/schema/BreweryPostQueryResult'; import CreateBeerPostValidationSchema from '@/services/BeerPost/schema/CreateBeerPostValidationSchema'; import sendCreateBeerPostRequest from '@/requests/BeerPost/sendCreateBeerPostRequest'; import UploadImageValidationSchema from '@/services/schema/ImageSchema/UploadImageValidationSchema'; import sendUploadBeerImagesRequest from '@/requests/BeerImage/sendUploadBeerImageRequest'; import toast from 'react-hot-toast'; import createErrorToast from '@/util/createErrorToast'; import Button from './ui/forms/Button'; import FormError from './ui/forms/FormError'; import FormInfo from './ui/forms/FormInfo'; import FormLabel from './ui/forms/FormLabel'; import FormSegment from './ui/forms/FormSegment'; import FormSelect from './ui/forms/FormSelect'; import FormTextArea from './ui/forms/FormTextArea'; import FormTextInput from './ui/forms/FormTextInput'; interface BeerFormProps { brewery: z.infer; styles: BeerStyle[]; } const CreateBeerPostWithImagesValidationSchema = CreateBeerPostValidationSchema.merge( UploadImageValidationSchema, ); const CreateBeerPostForm: FunctionComponent = ({ styles = [], brewery, }) => { const { register, handleSubmit, formState: { errors, isSubmitting }, } = useForm>({ resolver: zodResolver(CreateBeerPostWithImagesValidationSchema), defaultValues: { breweryId: brewery.id }, }); const onSubmit: SubmitHandler< z.infer > = async (data) => { if (!(data.images instanceof FileList)) { return; } try { const loadingToast = toast.loading('Creating beer post...'); const beerPost = await sendCreateBeerPostRequest(data); await sendUploadBeerImagesRequest({ beerPost, images: data.images }); await router.push(`/beers/${beerPost.id}`); toast.dismiss(loadingToast); toast.success('Created beer post.'); } catch (e) { createErrorToast(e); } }; return (
Name {errors.name?.message} Style {errors.styleId?.message} ({ value: style.id, text: style.name, }))} placeholder="Beer style" message="Pick a beer style" />
ABV {errors.abv?.message}
IBU {errors.ibu?.message}
Description {errors.description?.message} Images {(errors.images as FieldError | undefined)?.message}
); }; export default CreateBeerPostForm;