I have an app that searches the name of the pokemon reads the data eg. name, height, weight. Now when it comes to the abilities I can’t get the value of the name of the ability.
here’s my app.js
JavaScript
x
73
73
1
import React, { Component } from 'react';
2
import './App.css';
3
import Request from 'superagent';
4
5
class App extends Component {
6
constructor(props) {
7
super(props);
8
this.state = {
9
body: "",
10
value: "",
11
name: "",
12
abilities: "",
13
order: "",
14
weight: "",
15
height: ""
16
};
17
18
this.handleChange = this.handleChange.bind(this);
19
this.handleSubmit = this.handleSubmit.bind(this);
20
}
21
22
handleChange(event) {
23
this.setState({value: event.target.value.toLowerCase()});
24
}
25
26
handleSubmit(event) {
27
var url = "https://pokeapi.co/api/v2/pokemon/"+this.state.value;
28
Request.get(url).then((response) => {
29
this.setState({
30
body: response.body,
31
height: response.body.height,
32
weight: response.body.weight,
33
abilities: response.body.abilities,
34
name: response.body.name,
35
order: response.body.order,
36
picFront: response.body.sprites.front_default,
37
picBack: response.body.sprites.back_default,
38
picShiny: response.body.sprites.front_shiny,
39
40
41
});
42
});
43
event.preventDefault();
44
}
45
46
render() {
47
48
return (
49
<div className="flex">
50
<div className="App">
51
<h1>Search Pokemon</h1>
52
<form onSubmit={this.handleSubmit}>
53
<input type="text" value={this.state.value} onChange={this.handleChange} />
54
<input type="submit" value="Submit" />
55
</form>
56
</div>
57
<div className="app2">
58
<h1><small>{this.state.order} </small>{this.state.name}</h1>
59
<img alt={this.state.name} src={this.state.picFront}/>
60
<img alt={this.state.name} src={this.state.picBack}/>
61
<img alt={this.state.name} src={this.state.picShiny}/>
62
<p>Height: {this.state.height}</p>
63
<p>Weight: {this.state.weight}</p>
64
<p>list of abilities here</p>
65
</div>
66
</div>
67
68
);
69
}
70
};
71
72
73
export default App;
Advertisement
Answer
Abilities has this structure. You can check this by logging this.state.abilities
JavaScript
1
19
19
1
abilities: [
2
{
3
slot: 3,
4
is_hidden: true,
5
ability: {
6
url: "https://pokeapi.co/api/v2/ability/31/",
7
name: "lightning-rod"
8
}
9
},
10
{
11
slot: 1,
12
is_hidden: false,
13
ability: {
14
url: "https://pokeapi.co/api/v2/ability/9/",
15
name: "static"
16
}
17
}
18
]
19
It’s just an array. What you need to do is iterate over this array to retrieve those name values. There are a lot of ways to do this but the general logic should be something like:
“For each of these objects in the abilities array, I need to retrieve ability.name”
I am going to post some code here but try to solve it yourself before looking at mine.
In your p tag, you can do this
JavaScript
1
6
1
<p>
2
list of abilities here:
3
{this.state.abilities && this.state.abilities.map((abilityObject) =>
4
abilityObject.ability.name).join(', ')}
5
</p>
6