Reputation: 217
Hi guys im trying to do functional setState in react, but i cant seem to achive it right now i have a hanlder that is supposed to set the state of this.state.siocId
handleChange(e) {
const {value} = e.target;
this.setState(state => ({
siocId: {...state.siocId, siocId: value}
}));
}
but this is setting this.state.siocId.siocId = value
, hoy can i do to get this.state.siocId = value
? i tried this line with no success siocId: {...state, siocId: value}
Upvotes: 0
Views: 295
Reputation: 9338
If you want to setstate functionally, then use this pattern
handleChange(e) {
const {value} = e.target;
this.setState(function(prevState, props){
return {siocId: value}
});
}
Also refer these articles functional-setstate and Function in setstae for more info
However, u should use functional setstae when the value of the state depends on the previous state. This is used because setstate calls are not run immediately
Use the below pattern if ur state is not dependent on previous state
handleChange(e) {
const {value} = e.target;
this.setState({
siocId: value
});
}
Upvotes: 1
Reputation: 179
You're overcomplicating this -
handleChange(e) {
const {value} = e.target;
this.setState({
siocId: value
});
}
Upvotes: 0
Reputation: 281636
You don't need to use functional setState
to achieve what you want, you would simple write
handleChange(e) {
const {value} = e.target;
this.setState({
siocId: value
});
}
and this would give you this.state.siocId = value
Upvotes: 0