So I’m quite new to web dev but I’m trying to build my first front-end app that simply fetches some data from an API and displays it. When I console.log()
my promise, it returns an array of objects, which is what I want and what I expect from the promise. But, when I try to set my component’s state to that same promised array, React is throwing this error:
Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
Here is the relevant code:
JavaScript
x
41
41
1
const config = {
2
method: 'get',
3
url: 'http://ergast.com/api/f1/2020/drivers.json',
4
headers: {}
5
};
6
7
export default class DriverList extends Component {
8
9
state = {
10
drivers: []
11
}
12
13
componentDidMount() {
14
axios(config)
15
.then(res => {
16
console.log(res.data.MRData.DriverTable.Drivers)
17
this.setState({
18
drivers: res.data.MRData.DriverTable.Drivers // *** Error pointing to this ***
19
});
20
console.log(this.drivers)
21
})
22
.catch(err => {
23
console.log(err)
24
});
25
}
26
27
render() {
28
return (
29
<div>
30
{this.state.drivers.map(driver =>
31
<Driver
32
firstName={driver.giveName}
33
lastName={driver.familyName}
34
driverID={driver.driverId}
35
/>)
36
}
37
</div>
38
)
39
}
40
}
41
Any help with this would be appreciate!
Advertisement
Answer
I think there’s not actual data, but Promise
.
How about trying this??
JavaScript
1
16
16
1
componentDidMount() {
2
this.getDrivers();
3
}
4
5
getDrivers = async () => {
6
try {
7
const res = await axios(config);
8
const drivers = res.data.MRData.DriverTable.Drivers;
9
this.setState({
10
drivers
11
});
12
} catch (err) {
13
console.log(err);
14
}
15
};
16