JavaScript
x
50
50
1
class Home extends Component {
2
constructor(props) {
3
super(props);
4
this.state = {
5
data: [],
6
isLoaded: false,
7
};
8
}
9
10
componentDidMount() {
11
fetch("https://reqres.in/api/users?page=2")
12
.then((res) => res.json())
13
.then((json) => {
14
this.setState({
15
isLoaded: true,
16
data: json,
17
18
});
19
});
20
}
21
22
render() {
23
24
var { isLoaded, data }= this.state;
25
26
if(!isLoaded){
27
return<div>Is isLoaded</div>
28
}
29
30
else{
31
32
return (
33
<div>
34
<ul>
35
{() =>
36
this.state.data.map((data, index) => (
37
<li key={index}>Email: {data.email}</li>
38
))
39
}
40
;
41
</ul>
42
43
</div>
44
);
45
}
46
}
47
}
48
49
export default Home;
50
Hii All , I know this question is asked many times but I cant figure it out I’am getting the error. I have checked for all the questions similar to this but haven’t found specific solution if I use another link i.e, “https://jsonplaceholder.typicode.com/users” this one the code works fine .
Advertisement
Answer
The returned data from https://reqres.in/api/users?page=2
is not an array, but an object with a data
property containing what you are looking for (an array). The result of the request is :
JavaScript
1
2
1
{"page":1,"per_page":6,"total":12,"total_pages":2,"data":[{"id":1,"email":"george.bluth@reqres.in","first_name":"George","last_name":"Bluth","avatar":"https://reqres.in/img/faces/1-image.jpg"},{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet","last_name":"Weaver","avatar":"https://reqres.in/img/faces/2-image.jpg"},{"id":3,"email":"emma.wong@reqres.in","first_name":"Emma","last_name":"Wong","avatar":"https://reqres.in/img/faces/3-image.jpg"},{"id":4,"email":"eve.holt@reqres.in","first_name":"Eve","last_name":"Holt","avatar":"https://reqres.in/img/faces/4-image.jpg"},{"id":5,"email":"charles.morris@reqres.in","first_name":"Charles","last_name":"Morris","avatar":"https://reqres.in/img/faces/5-image.jpg"},{"id":6,"email":"tracey.ramos@reqres.in","first_name":"Tracey","last_name":"Ramos","avatar":"https://reqres.in/img/faces/6-image.jpg"}],"support":{"url":"https://reqres.in/#support-heading","text":"To keep ReqRes free, contributions towards server costs are appreciated!"}}
2
So you cannot use map function, which is from the Array prototype, on the result of your request. You must access the data property first :
JavaScript
1
4
1
this.state.data.data.map((data, index) => ( // note the double data
2
<li key={index}>Email: {data.email}</li>
3
))
4
You could also assign json.data
to the state.data
to avoid the ugly .data.data
:
JavaScript
1
5
1
this.setState({
2
isLoaded: true,
3
data: json.data, // note the .data
4
});
5