Duke Dougal
Duke Dougal

Reputation: 26366

In reactjs is it ok to execute async functions in componentDidMount and do a setstate in the resulting callback?

My understanding is that the right place to do my initial ajax data loading is in componentDidMount.

It seems to me that what I want to do is "setState" of the result of the several async functions that I will execute.

Thus I need to put the setState in the async callbacks.

Am I doing this right or wrong? Will it cause a problem to be executing setState from within async callbacks?

Upvotes: 4

Views: 763

Answers (2)

Peak Sornpaisarn
Peak Sornpaisarn

Reputation: 975

You can set async componentDidMount like this :

async componentDidMount() {
  const res = await fetch('https://example.com')
  const something = await res.json()
  this.setState({something})
}

Upvotes: 0

Michelle Tilley
Michelle Tilley

Reputation: 159115

Yes, that is perfectly fine. The only thing you'll want to watch out for is the fact that your Ajax request could finish after the component is unmounted for some reason; thus, you'll want to make sure everything gets cleaned up if your component is unmounted. See isMounted is an Antipattern for more information.

Upvotes: 1

Related Questions