Reputation: 319
I have nested form objects but I try to setState using one handler, somehow doesn't work
constructor() {
super()
this.state = {
form: {
name: '',
location: ''
}
}
}
handleFormInput = (event) => {
this.setState({
[this.state.form[event.target.name]]: event.target.value
})
setTimeout(() => {
console.log(this.state.form)
},50)
}
event.target.name
can be name and location.
Upvotes: 1
Views: 105
Reputation: 1415
setState is asynchronous, your state will properly update somehow after the call. Then render will be called again. Try checking your new state in render or in componentWillUpdate : https://facebook.github.io/react/docs/react-component.html#componentwillupdate
You should never look for a change in your state right after changing your state
Upvotes: 0
Reputation: 281854
You cannot directly access and modify a dynamic state within the setState
function, you would rather get a copy of the state object and modify it. Also as you may already know that setState
is async
and hence you have a setTimeout
function which is not necessary since setState
provides you a callback
function which is executed when state has changed.
handleFormInput = (event) => {
var form = {...this.state.form}
form[event.target.name] = event.target.value;
this.setState({
form
}, () => {this.state.form})
}
Upvotes: 1
Reputation: 1515
I think this code is not working properly:
this.setState({ [this.state.form[event.target.name]]: event.target.value })
alternative is :
handleFormInput = (event) => {
//New code
let obj = {}
obj[this.state.form[event.target.name]] = event.target.value
this.setState(obj,() => { console.log(this.state.form) })
}
to view updated state
, use callback function param of this.setState
Upvotes: 1