console.log prints the old state
causing error in eval
eg:- eval(“12*”)
this.setState({
displayFormula: this.state.displayFormula + this.state.displayTitle
});
console.log(this.state.displayFormula);
const res = eval(this.state.displayFormula);
this.setState({ displayTitle: res });
} ```
You can use the setState callback, or a lifecycle method, to log the state after a setState call. And if your setState depends on the current state you may have to use the updater function.
setState
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. If you need to set the state based on the previous state, read about the updater argument below.
State Updates May Be Asynchronous
If you need help with your code you will likely have to post a link to a live version, you can use something like Codesandbox.
1 Like