I'm trying to get data from an api so that I can display it when the page is loaded. I want to pass this data onto the Featured component. The api GET request works, however, I'm getting the error 'res' in not defined no-undef. I'm guessing it's because it's an async function and the state is being told to change before the data from the api has come back. However, I get the same error even if I take away the async and await. I have a few questions regarding this:
What is causing the issue?
How would you fix the issue?
Am I correct in using componentDidMount for what I'm trying to do?
Code is posted bellow. Thanks in advance!
class App extends React.Component {
state = { featuredMovies: [] };
async componentDidMount() {
await axios.get('apiurl').then(res => {
console.log(res.data)
});
this.setState({ featuredMovies: res.data });
}
render() {
return (
<div className="container section">
<Featured />
</div>
);
}
}