Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormData Returns empty data on form submission in react

I am trying to get the form data key-value pair object when the form is submitted, using the new FormData() constructor. But it always returns empty data.

I have already tried event.persist() to avoid react event pooling, but nothing worked


export default class Test extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    const target = event.target;
    const data = new FormData(target);
    console.log(data)
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="username">Enter username</label>
        <input id="username" name="username" type="text" />

        <button>Send data!</button>
      </form>
    );
  }
}

I am expecting an object that contains my form data in the following format

{ "username": "Value" }

like image 897
Waeez Avatar asked May 20 '19 05:05

Waeez


People also ask

How do I get form data on submit in Reactjs?

To get input values on form submit in React: Store the values of the input fields in state variables. Set the onSubmit prop on the form element. Access the values of the input fields in your handleSubmit function.

How do you prevent a form from clearing fields on submit React?

To prevent basic React form submit from refreshing the entire page, we call e. preventDefault . in the submit event handler. to create the onSubmit function that's set as the value of the onSubmit prop.

What does FormData return?

FormData.get() Returns the first value associated with a given key from within a FormData object.

How form submit works in React?

HTML form submission works differently when implementing it within a React. js component. Normally, the browser would render the HTML and, depending on the action , automatically submit the data of the form based on each element's name attribute. Although this default behavior still works in React.


2 Answers

I think you need to fetch it through looping. Try this

  var formData = new FormData(target);

   for (var [key, value] of formData.entries()) { 
   console.log(key, value);
  }

Hope it works.

like image 143
Zabih Ullah Avatar answered Sep 19 '22 05:09

Zabih Ullah


handleSubmit should be like this.

handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.target);
    fetch('my-api', {
      method: 'POST',
      body: data,
    });
  }

After form submit, in network tab you will find form data with key-value.

If you want to access single value,

const username = data.get('username');
like image 28
RIYAJ KHAN Avatar answered Sep 17 '22 05:09

RIYAJ KHAN