Reputation: 553
After storing the data from controlled form element, I want to reset the value of my input type to empty. In this method below setState is not setting it to empty. Not sure why.
handleSubmit = event => {
event.preventDefault();
this.props.dispatch(passengerActions.addPassenger(this.state.passenger));
this.setState({ ...this.state.passenger, firstName: "", lastName: "" });
};
The following method works
handleSubmit = event => {
event.preventDefault();
this.props.dispatch(passengerActions.addPassenger(this.state.passenger));
const passenger = {
...this.state.passenger,
firstName: "",
lastName: ""
};
this.setState({ passenger });
};
Please help me understand why the first method is not working. I am new to ReactJS.
Upvotes: 0
Views: 323
Reputation: 471
You should rewrite your 1st solution like: this.setState({ ...state, passenger: { firstName: “”, lastName: “” } })
Upvotes: -1
Reputation: 1074038
In the first one, you're spreading out your passenger
object at the top level of your state, and adding firstName
and lastName
at the top level as well.
You probably wanted to update passenger
, which is what you do in your second one:
this.setState({passenger: { ...this.state.passenger, firstName: "", lastName: "" }});
// −−−−−−−−−−−−^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^
But, whenever updating state based on existing state (the other fields in passenger
you're copying over), it's usually best to use the callback form because state updates are asynchronous and can get batched together:
this.setState(({passenger}) => ({passenger: { ...passenger, firstName: "", lastName: "" }}));
Upvotes: 3