0

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:

  1. What is causing the issue?

  2. How would you fix the issue?

  3. 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>
        );
    }
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
BoJack
  • 225
  • 1
  • 2
  • 7

1 Answers1

2

You're almost right. Just change this part:

async componentDidMount() {
  const res = await axios.get('apiurl');
  this.setState({ featuredMovies: res.data });
}

So to answer your questions:

  1. What is causing the issue?
    The problem with your code is that you don't have res out of the function.
  2. How would you fix the issue?
    Using the above solution.
  3. Am I correct in using componentDidMount for what I'm trying to do?
    Almost right. Your approach is right.
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252