Home > other >  Trouble with react hook form, using file as input
Trouble with react hook form, using file as input

Time:04-27

I have a form ingesting some strings and a file. The strings are working correctly, but whenever I check to see if the file has been registered correctly, it's always null.

The interface I'm using:

export interface myDetail {
  myText: string;
  Picture?: File;
}

Form group for image (not working):

<Form
     onSubmit={handleSubmit((data) => {
        console.log(data);
        setDetail({ ...myDetail, ...data });
     })}
  >
     <Form.Group controlId="formFile" className="mb-3">
         <Form.Label>Upload Picture</Form.Label>
         <Form.Control as="input" type="file" {...register('Picture')} />
      </Form.Group>

button:

<AsyncButton type="submit">Save</AsyncButton>

The string variables get assigned fine, but when I check data, the Picture is set to "0, {}"

Thanks for any help

CodePudding user response:

I don't know what the Form.*** component is, so I think it's difficult to answer.
Can it be reproduced with code-sandobox etc.?

If Form.Control is built as a controlled-component,
you should be able to successfully connect to RHF using useController or Controller.

CodePudding user response:

JSON.stringify does not parse File objects. Your data is most likely a FileList containing one File object, hence the "0,{}". 0th index in the array, containing an unserializable File object.

If you break at your console.log(data) and examine the data in a debugger, you'll most likely see your File object as expected. The data is there, but not being displayed to the console. Please see this post for more info:

How can I serialize an input File object to JSON?

Alternatively, you can use FileReader to read the File using readAsDataURL().

  • Related