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" }
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.
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.
FormData.get() Returns the first value associated with a given key from within a FormData object.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With