setState for an array of objects in handleChange is not working setState for an array of objects in handleChange is not working elasticsearch elasticsearch

setState for an array of objects in handleChange is not working


setState is asynchronous.so it will work like this:

this.setState({ MP3info: body.hits.hits.map(i => i._source) }, () => {    console.log(this.state.MP3info)})

from documentation:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.


After calling setState, you cannot expect the state to be updated immediately since setState is an asynchronous operation.

However, there is an optional 2nd parameter of a callback function which you can use in setState, if you want to do something immediately after updating the state.

this.setState({        value: newStateValue,    }, () => {     const { value } = this.state; // access the updated value here    })

Please follow this beautiful explanation of how setState works! link

Also:

When not to use the callback:

React docs recommend that you use the lifecycle events.

Here’s why.

PureComponent and shouldComponentUpdate can be used to tune up a component’s performance. They work by preventing lifecycle methods from firing when props and state haven’t changed.

The setState callback fires regardless of what shouldComponentUpdate returns. So, the setState callback will fire, even when state hasn’t changed.

So.. Don’t be afraid to use the setState callback. It’s there for a reason. But when you do, keep an eye on shouldComponentUpdate, if you see any shiftiness.