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
x
49
49
1
class PokemonGenerator extends Component {
2
totalPokemon = 151
3
4
constructor() {
5
super()
6
this.state = {
7
currentImg: "https://d.newsweek.com/en/full/822411/pikachu-640x360-pokemon-anime.jpg?w=1600&h=1200&q=88&f=3ed1c0d6e3890cbc58be90f05908a8f5",
8
currentName: "",
9
wrongChoice1: "",
10
wrongChoice2: "",
11
wrongChoice3: "",
12
}
13
this.handleClick = this.handleClick.bind(this)
14
this.handleChange = this.handleChange.bind(this)
15
}
16
17
handleClick(event) {
18
// event.preventDefault()
19
const randNum1 = Math.floor(Math.random() * this.totalPokemon)
20
const randNum2 = Math.floor(Math.random() * this.totalPokemon)
21
const randNum3 = Math.floor(Math.random() * this.totalPokemon)
22
const randNum4 = Math.floor(Math.random() * this.totalPokemon)
23
24
25
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum1)
26
.then(response => response.json())
27
.then(response => {
28
this.setState({
29
currentImg: response['sprites']['front_default'],
30
currentName: response.name
31
}, function() {console.log(`CORRECT ANSWER: ${this.state.currentName}`)})
32
})
33
34
this.fetchApiAndSetStateForWrongGuesses(randNum2, this.state.wrongChoice1)
35
this.fetchApiAndSetStateForWrongGuesses(randNum3, this.state.wrongChoice2)
36
this.fetchApiAndSetStateForWrongGuesses(randNum4, this.state.wrongChoice3)
37
}
38
39
fetchApiAndSetStateForWrongGuesses(randNum, wrongGuess) {
40
41
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum)
42
.then(response => response.json())
43
.then(response => {
44
this.setState({
45
wrongGuess: response.name
46
}, function () {console.log(`Wrong Choice: ${wrongGuess}`)})
47
})
48
}
49
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
1
8
1
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum)
2
.then(response => response.json())
3
.then(response => {
4
this.setState({
5
wrongGuess: response.name
6
}, function () {console.log(`Wrong Choice: ${this.state.wrongGuess}`)})
7
})
8