this.setState doesnt change the state

Multi tool use
this.setState doesnt change the state
So, I am trying to change the state using previous state, but it doesnt change whatsoever. Can anyone tell me whats the problem pls?
handleToggleComplete = (key, complete) => {
itemIndex = this.state.items.findIndex(item => item.key === key);
console.log('before: ', this.state.items);
this.setState(prevState => {
return {
...prevState,
items: [
...prevState.items,
prevState.items[itemIndex]: {
completed: true,
text: 'hardcoded value'
}
]
}
});
console.log('after: ', this.state.items);
}
Logs:
before:
[{…}]
{key: 1530370127933, completed: false, text: "some value"}
after:
[{…}]
{key: 1530370127933, completed: false, text: "some value"}
1 Answer
1
this.setState
doesn't change the state immediately. It re-renders the component and with the updated state. So naturally you will not see the updated state in your function.
this.setState
Here is an app that demonstrates exactly that. I displayed in the console the current value of the state and render it with the button:
class App extends React.Component {
constructor (props) {
super(props)
this.state = {
myState: 0
}
}
handleClick () {
let incrementState = this.state.myState + 1
console.log('State before increment:', this.state.myState)
this.setState({myState: incrementState})
console.log('State AFTER increment:', this.state.myState, 'nSee, it's still the same BUT the component has been updated (look at the number)!')
}
render() {
const { myState } = this.state
return (<div>
<h1>{myState}</h1>
<button onClick={() => this.handleClick()}>Increment State</button>
</div>);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
<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>
<div id="app"></div>
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.