0

How would I convert my FormData into an object than JSON.stringify that? I think a reason why my values in the API are not being populated with my data is because endpoint expects JSON data.

handleSubmit:

handleSubmit(event) {
      event.preventDefault();

      const data = new FormData(event.target);

      fetch('http://localhost:8080/seniorproject/addUser', {
        method: 'POST',
        body: data,
      });

      console.log(data);
    }

Form:

<form onSubmit={this.handleSubmit}>
          <label htmlFor="First Name">Enter First Name</label>
          <input id="firstName" name="firstName" type="text" />

          <label htmlFor="Last Name">Enter your Last Name</label>
          <input id="lastName" name="lastName" type="lastName" />

          <label htmlFor="studentID">Enter your student id</label>
          <input id="studentID" name="studentID" type="text" />

          <label htmlFor="Email">Enter your email</label>
          <input id="email" name="email" type="text" />

          <label htmlFor="Password">Enter your password</label>
          <input id="password" name="password" type="text" />

          <button>Send data!</button>
        </form>
1
  • may i know if u r importing redux-form ? Commented Apr 17, 2019 at 13:58

1 Answer 1

2

You could use the formData.entries() method to loop over all the entries in the FormData and construct a JSON object, like so:

const json = {};
Array.from(formData.entries()).forEach(([key, value]) => {
  json[key] = value;
})

JSON.stringify(json)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.