2 years ago

#62362

test-img

user42488

Proper way of Uploading Files Using React Hook Form with Axios

I'd like to upload files along with my form data using react hook form and axios. I've found this great video explaining how to create a simple example. However, I did not find a nice solution how to get the data across to the backend using axios. Consider the simple example below:

function Test() {
    const {register, handleSubmit} = useForm();
    const onSubmit = (data) => {
        console.log(data);
    };
    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <input {...register("name")} />
            <input {...register("picture")} type="file"/>
            <button>Submit</button>
        </form>
    );
}

Now the submit function I came up with - and that does work apparently - looks somewhat like this:

const onSubmit = (data => {
     const formData = new FormData();
     for (const [key, value] of Object.entries(data)) {
        formData.append(key, value);
     }

    api.submitPost(formData, {headers: {'Content-Type': 'multipart/form-data'}})
       .then((response) => {
            console.log(response);
       })
       .catch((error) => {
            console.log(error);
       });
};

However, it does not feel right to manually iterate through the data and transfer it onto the FormData. Is there a proper way of doing this?

reactjs

file-upload

axios

react-hook-form

0 Answers

Your Answer

Accepted video resources