Home > front end >  i am trying to upload file using react hook form and i used useController function and i am getting
i am trying to upload file using react hook form and i used useController function and i am getting

Time:06-25

I am creating a multipart form in which uses usecontrol method of react hook form . i declarer default value

const methods = useForm({
  defaultValues: {
    email: "",
    course: "Enginering",
    program: "B.tech",
    mobielNumber: "",
    dob: "",
    gender: "",
    cityName: "",
    state: "",
    file:"",
  },
});  

but i am getting file value is null can any one tell me were i have to declare file input so i can get value .

I seen documentation there they told

File typed input will need to be managed at the app level due to the ability to cancel file selection and FileList object.

what these means where i have to declare it .

CodePudding user response:

After a day I figure it out that some how we need to explicitly setValue when we post file with useController

And also somehow the field object has value inside of it, it will get e.target.value as default and it something like ...fakepath/.. which not true because files upload inside e.target.files

const { setValue } = useForm({
  defaultValues: {
     file: "",
    //.....
  }
})
const { field: { name, ref } } = useController({name, control, rules, defaultValue}); 

Don't include value inside as a result of useController because the value inside field gonna cause the error if it use together with files

const handleChange = (e) => {
   setValue('file', e.target.files);
}

<input name={name} ref={ref} type="file" multiple onChange={handleChange}/>

When you submit it, you gonna see the FileList, if not or something like fakepath as i said you need to manually setValue to e.target.files

  • Related