Reputation: 64
When trying to use setState to update a customer age, the object is mutated before setState, but setState doesn't update the existing object.
customerOnChange(event, field) {
//Customer age right now is 80
var customer = { ...this.state.customer };
customer.age = "14";
console.log('The age of the customer is ', customer.age) //This shows up correctly
this.setState({
customer
},
() => {
console.log(this.state.customer.age) //Customer age still 80
});
}
Ignore the object type being a String(I had to generalize the code before posting), property types match up correctly, but setState doesn't seem to be updating the customer
object.
I've also tried something like
this.setState({customer: newCustomer})
with no luck.
Upvotes: 0
Views: 300
Reputation: 14927
I'm guessing you haven't bound this
to your customerOnChange(event, field)
event. Try writing it as
customerOnChange = (event, field) => {
. See the snippet below.
As an alternative, you can bind this
in the constructor, if you have one. Like so:
constructor(props){
super(props);
this.state={
customer: { age: 80 }
}
this.customerOnChange = this.customerOnChange.bind(this);
}
class Thingy extends React.Component {
state = {
customer: {
age: "80"
}
}
customerOnChange = (event, field) => {
//Customer age right now is 80
const customer = { ...this.state.customer};
customer.age = event.target.value;
console.log('The age of the customer is ', customer.age) //This shows up correctly
this.setState({
customer
},
() => {
console.log(this.state.customer.age) //Customer age still 80
});
}
render() {
const {age} = this.state.customer;
return (
<div >
<input type="number" value={age} onChange={this.customerOnChange} />
<p>Customers Age:{age}</p>
</div>
);
}
}
// Render it
ReactDOM.render( <
Thingy title = "I'm the thingy" / > ,
document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Upvotes: 1