import { zodResolver } from '@hookform/resolvers/zod'; import { BeerType } from '@prisma/client'; import router from 'next/router'; import { FunctionComponent, useState } from 'react'; import { useForm, SubmitHandler, FieldError } from 'react-hook-form'; import { z } from 'zod'; import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult'; import CreateBeerPostValidationSchema from '@/services/BeerPost/schema/CreateBeerPostValidationSchema'; import sendCreateBeerPostRequest from '@/requests/sendCreateBeerPostRequest'; import UploadImageValidationSchema from '@/services/types/ImageSchema/UploadImageValidationSchema'; import sendUploadBeerImagesRequest from '@/requests/sendUploadBeerImageRequest'; import ErrorAlert from './ui/alerts/ErrorAlert'; 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 { breweries: z.infer[]; types: BeerType[]; } const CreateBeerPostWithImagesValidationSchema = CreateBeerPostValidationSchema.merge( UploadImageValidationSchema, ); const CreateBeerPostForm: FunctionComponent = ({ breweries = [], types = [], }) => { const { register, handleSubmit, formState } = useForm< z.infer >({ resolver: zodResolver(CreateBeerPostWithImagesValidationSchema), }); const { errors, isSubmitting } = formState; const [error, setError] = useState(''); const onSubmit: SubmitHandler< z.infer > = async (data) => { if (!(data.images instanceof FileList)) { return; } const { breweryId, typeId, name, abv, ibu, description } = data; try { const response = await sendCreateBeerPostRequest({ breweryId, typeId, name, abv, ibu, description, }); await sendUploadBeerImagesRequest({ beerPost: response, images: data.images, }); router.push(`/beers/${response.id}`); } catch (e) { if (!(e instanceof Error)) { setError('Something went wrong'); return; } setError(e.message); } }; return (
{error && }
Name {errors.name?.message}
Brewery {errors.breweryId?.message} ({ value: brewery.id, text: brewery.name, }))} placeholder="Brewery" message="Pick a brewery" />
Type {errors.typeId?.message} ({ value: beerType.id, text: beerType.name, }))} placeholder="Beer type" message="Pick a beer type" />
ABV {errors.abv?.message}
IBU {errors.ibu?.message}
Description {errors.description?.message} Images {(errors.images as FieldError | undefined)?.message}
); }; export default CreateBeerPostForm;