trinhmatt
trinhmatt

Reputation: 33

(React) setState() callback not firing after state change

I am using React for this project.

I need to read the state directly after I set it (using the callback), but when I print the state to the screen using the callback I get the values of the previous state. Using devtools I can see that the state does change, so that is not the problem. I looked at the docs and it said the callback is supposed to fire after the state is changed and the component updates, but I am not seeing that behaviour in my component. I am also not getting any error messages.

Here is the code, thanks for your help!

onAnswerSelect = (e) => {
    const selectedAnswer = e.target.value;
    //Set the state, then simulate a click on the submit button
    this.setState(() => ({selectedAnswer}), this.simulateClick(e))
  }

simulateClick = (e) => {
    console.log(this.state.selectedAnswer)
    e.target.parentNode.parentNode.firstChild.click()
  }

Upvotes: 2

Views: 4756

Answers (1)

Prakash Sharma
Prakash Sharma

Reputation: 16472

You are not passing function to setState callback but calling it. You can pass a function and parameter using bind function like this

this.setState(() => ({selectedAnswer}), this.simulateClick.bind(this,e))

The other way is to use a closure. You can make simulateClick function to return a function like this

simulateClick = (e) => () => {
    console.log(this.state.selectedAnswer)
    e.target.parentNode.parentNode.firstChild.click()
  }

this.setState(() => ({selectedAnswer}), this.simulateClick(e))

Upvotes: 6

Related Questions