next-safe-action / adapter-react-hook-form

Seamlessly integrate next-safe-action with react-hook-form.
https://www.npmjs.com/package/@next-safe-action/adapter-react-hook-form
MIT License
36 stars 0 forks source link

Couldn't figure out how to make this work with a file input #7

Open web-dev-sayantan opened 1 week ago

web-dev-sayantan commented 1 week ago

The library makes the react-hook-form with next-safe-actions usage a lot simpler. Thanks a ton for this. However, I'm not able to use file input with the setup provided in the examples. I'm using react-dropzone along with react-hook-form to get the image from the user and validate it against my zod schema and the react-hook-form control for the file contains the File Object. Yet, onSubmit I'm gettingt the following error: "Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported."

My zod schema:

const formSchema = z.object({
  bannerForDesktop: z
      .instanceof(File, { message: 'Upload a banner suitable for desktop view.' })
      .refine(file => file.size <= MAX_IMAGE_SIZE, {
        message: `Image size must be less than ${
          MAX_IMAGE_SIZE / 1024 / 1024
        }MB.`,
      })
      .refine(file => ACCEPTED_IMAGE_TYPES.includes(file.type), {
        message: `Image types allowed: ${ACCEPTED_IMAGE_TYPES.join(', ')}.`,
      })
      .optional()
      .nullable(),
})

The formSubmission part:

  const {
      form,
      action: { isExecuting },
      handleSubmitWithAction,
      resetFormAndAction,
    } = useHookFormAction(createEventAction, zodResolver(eventFormSchema), {
      formProps: {
        mode: 'onChange',
        defaultValues: {
          bannerForDesktop: null
        },
        },
      },
      actionProps: {
        onSuccess: () => {
          toast({
            title: 'Form submitted successfully',
          })
          resetFormAndAction()
        },
      },
    })

The part where I connect it to the Form:

  <Form {...form}>
      <form
        onSubmit={handleSubmitWithAction}
        className='grid gap-4 md:w-full'
      >
          ...
          ...
      </form>
  </Form>

The file object that is attached to the formObject and validates properly against the zod schema in browser: image

Let me if any other context is needed.

TheEdoRan commented 1 week ago

Are you using Node.js < 20 (18) perhaps?