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?
class PokemonGenerator extends Component { totalPokemon = 151 constructor() { super() this.state = { currentImg: "https://d.newsweek.com/en/full/822411/pikachu-640x360-pokemon-anime.jpg?w=1600&h=1200&q=88&f=3ed1c0d6e3890cbc58be90f05908a8f5", currentName: "", wrongChoice1: "", wrongChoice2: "", wrongChoice3: "", } this.handleClick = this.handleClick.bind(this) this.handleChange = this.handleChange.bind(this) } handleClick(event) { // event.preventDefault() const randNum1 = Math.floor(Math.random() * this.totalPokemon) const randNum2 = Math.floor(Math.random() * this.totalPokemon) const randNum3 = Math.floor(Math.random() * this.totalPokemon) const randNum4 = Math.floor(Math.random() * this.totalPokemon) fetch('https://pokeapi.co/api/v2/pokemon/' + randNum1) .then(response => response.json()) .then(response => { this.setState({ currentImg: response['sprites']['front_default'], currentName: response.name }, function() {console.log(`CORRECT ANSWER: ${this.state.currentName}`)}) }) this.fetchApiAndSetStateForWrongGuesses(randNum2, this.state.wrongChoice1) this.fetchApiAndSetStateForWrongGuesses(randNum3, this.state.wrongChoice2) this.fetchApiAndSetStateForWrongGuesses(randNum4, this.state.wrongChoice3) } fetchApiAndSetStateForWrongGuesses(randNum, wrongGuess) { fetch('https://pokeapi.co/api/v2/pokemon/' + randNum) .then(response => response.json()) .then(response => { this.setState({ wrongGuess: response.name }, function () {console.log(`Wrong Choice: ${wrongGuess}`)}) }) }
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.
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum) .then(response => response.json()) .then(response => { this.setState({ wrongGuess: response.name }, function () {console.log(`Wrong Choice: ${this.state.wrongGuess}`)}) })