I’m learning React and now I’m trying to do a get request and list with map but when I run this code they come up with this error “Unhandled Rejection (TypeError): this.state.features.map is not a function”. I have already searched this but I do not understand what is going on.
JavaScript
x
48
48
1
import React, { Component } from 'react';
2
import './App.css';
3
4
class App extends Component {
5
6
constructor() {
7
super();
8
this.state = {
9
features: [{
10
id: 1,
11
name: 'Test',
12
count: 1
13
}]
14
}
15
}
16
17
componentWillMount() {
18
fetch("http://demo6085176.mockable.io/features")
19
.then(response => response.json())
20
.then(json => {
21
console.log(json);
22
this.setState({
23
features: json,
24
});
25
});
26
console.log(this.state.features)
27
28
}
29
30
render() {
31
return (
32
<div className="App">
33
<ul>
34
{
35
this.state.features.map(function(feature){
36
return (
37
<li key={feature.id}><button type="button">Upvote</button> ({feature.count}) <span>{feature.name}</span></li>
38
)
39
})
40
}
41
</ul>
42
</div>
43
);
44
}
45
}
46
47
export default App;
48
Advertisement
Answer
In your componentWillMount, just do this:
JavaScript
1
9
1
componentWillMount() {
2
fetch("http://demo6085176.mockable.io/features")
3
.then(response => response.json())
4
.then(json => {
5
console.log(json);
6
this.setState({ features: json.features });
7
});
8
}
9
The response you get from the API is an object which has a key of features
which is an array of objects of the data you want.