Waeez
Waeez

Reputation: 339

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

Upvotes: 13

Views: 21851

Answers (6)

Amani Amani
Amani Amani

Reputation: 11

It is simple

const formData = new FormData(e.target);

const inputs = Object.fromEntries(formData);

Upvotes: 0

lhmt
lhmt

Reputation: 21

Just elaborate more on Zabih's answer, an alternative to looping is to convert the entries to an object

  const submitForm = async (e: FormEvent) => {
    e.preventDefault();

    const form = e.target as HTMLFormElement;

    const formData = new FormData(form);
    const formDataEntries = formData.entries();

    const myData = Object.fromEntries(formDataEntries);
    console.log(myData);
  };

Upvotes: 0

Роман Зыков
Роман Зыков

Reputation: 595

one of if you are using React, just use htmlType tag

<Form.Item>
  <Button type="primary" htmlType="submit" />
    Submit action
  </Button>
</Form.Item>

Upvotes: -1

Mattia Fantoni
Mattia Fantoni

Reputation: 955

In my case I had to use this generic code snippet

    const form = event.target;
    const data = {};
    for (let i=0; i < form.elements.length; i++) {
        const elem = form.elements[i];
        data[elem.name] = elem.value
    }

I don't know the reason of this behaviour but it may be because the input inside form are not a part of the DOM anymore

Upvotes: 1

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

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');

Upvotes: 3

Zabih Ullah
Zabih Ullah

Reputation: 605

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.

Upvotes: 33

Related Questions