1

Is it OK if I use async in front of componentDidMount like this?

async componentDidMount() {
    const key = '11a03b332b43ad4cde5';
    try {
      const response = await axios.get('https://api.unsplash.com/photos/?client_id=' + key);
      this.setState({ imgs: response.data });
    } catch (err) {
      console.log('Error happened during fetching!', err);
    }
  }

It's working. But I wanted to ask to see if it is ok or is there any drawback to it.

Thanks

user1941537
  • 6,097
  • 14
  • 52
  • 99

1 Answers1

1

Yes it's perfectly fine. You are even encouraged to make your http request calls (like your get request with axios there) in componentDidMount(), so it only makes sense to be able to use async await there. However keep in mind you can also use promises and .then instead, which in those cases mean you do not need to add async to componentDidMount().

Darkphoton
  • 506
  • 4
  • 14