import { FunctionComponent } from 'react'; import router from 'next/router'; import { zodResolver } from '@hookform/resolvers/zod'; import { BeerStyle } from '@prisma/client'; import toast from 'react-hot-toast'; import { useForm, SubmitHandler, FieldError } from 'react-hook-form'; import { z } from 'zod'; import BreweryPostQueryResult from '@/services/posts/brewery-post/schema/BreweryPostQueryResult'; import CreateBeerPostValidationSchema from '@/services/posts/beer-post/schema/CreateBeerPostValidationSchema'; import UploadImageValidationSchema from '@/services/schema/ImageSchema/UploadImageValidationSchema'; import createErrorToast from '@/util/createErrorToast'; import { sendCreateBeerPostRequest } from '@/requests/posts/beer-post'; import sendUploadBeerImagesRequest from '@/requests/images/beer-image/sendUploadBeerImageRequest'; 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({ body: { name: data.name, description: data.description, abv: data.abv, ibu: data.ibu, }, breweryId: data.breweryId, styleId: data.styleId, }); 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;