Skip to content
Advertisement

Why is my setState not working when passed as an argument to a function?

For the function fetchApiAndSetStateForWrongGuesses() I pass it two parameters called randNum and wrongGuess. randNum is just a number but wrongGuess is supposed to be a state. The problem is that when I pass wrongGuess to the function fetchApiAndSetStateForWrongGuesses() the setState doesn’t works. By the time it hits the console.log it just prints out an empty string because thats what the constructor initialized it to be. How can I get it so that setState actually works depending on what state I pass to it?

JavaScript

Advertisement

Answer

In your callback function, wrongGuess is still bound to the argument that you passed to the function. setState updates this.state, so you need to access the new value from there.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement