javascriptreactjsdomdom-eventsform-data

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" }


Solution

  • 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.