简体   繁体   中英

Unable to get the formData values of file upload using react hook form

I am building a form with some text inputs and a file upload option. I am using react-hook-form library to achieve this. This is the link for the library https://react-hook-form.com/ . I have developed a small codesandbox for the same but it consists of only the file upload option. I am unable to get the file values inside formdata. It would be of real help to me if someone could tell me what is wrong here. Any help would be appreciated and thanks in advance. Here is the code sandbox link. Codesandbox

First with React-Hook-Form you can validate your input even file's input. You can use Yup for that. Second, to get value you just to initialize a new FormData , like this:

import React from "react";
import { useForm } from "react-hook-form";
import ReactDOM from "react-dom";

import "./styles.css";

const defaultValues = {
  test: [
    {
      name: "useFieldArray1",
      nestedArray: [{ field1: "field1", field2: "field2" }]
    },
    {
      name: "useFieldArray2",
      nestedArray: [{ field1: "field1", field2: "field2" }]
    }
  ]
};

function App() {
  const {
    control,
    register,
    handleSubmit,
    getValues,
    errors,
    reset,
    setValue
  } = useForm({
    defaultValues
  });

  const onSubmit = (data) => {
    // data in my project consists of other input data as well
    const uploads = new FormData();
    uploads.append("source", data.source[0]);
    console.log(uploads)
    // you can now make an API call if you want
    // enter code here
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <h1>Array of Array Fields</h1>

      <input type="file" ref={register} name="source" />
      <button type="button" onClick={() => reset(defaultValues)}>
        Reset
      </button>

      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

you can use this uploads to do whatever you want, like API call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM