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:
const config = { method: 'get', url: 'http://ergast.com/api/f1/2020/drivers.json', headers: {} }; export default class DriverList extends Component { state = { drivers: [] } componentDidMount() { axios(config) .then(res => { console.log(res.data.MRData.DriverTable.Drivers) this.setState({ drivers: res.data.MRData.DriverTable.Drivers // *** Error pointing to this *** }); console.log(this.drivers) }) .catch(err => { console.log(err) }); } render() { return ( <div> {this.state.drivers.map(driver => <Driver firstName={driver.giveName} lastName={driver.familyName} driverID={driver.driverId} />) } </div> ) } }
Any help with this would be appreciate!
Advertisement
Answer
I think there’s not actual data, but Promise
.
How about trying this??
componentDidMount() { this.getDrivers(); } getDrivers = async () => { try { const res = await axios(config); const drivers = res.data.MRData.DriverTable.Drivers; this.setState({ drivers }); } catch (err) { console.log(err); } };