tys
tys

Reputation: 699

componentDidMount order between parent and child components for asynchronous code

In react, the componentDidMount() method of child components is invoked before that of parent components, as shown here and here.

However, this is not the case if the child's componentDidMount() contains asynchronous code (e.g. Fetch API).

How do I run the parent's componentDidMount() only after the child's asynchronous componentDidMount is resolved ?

Upvotes: 4

Views: 727

Answers (2)

vatz88
vatz88

Reputation: 2452

A better way to do whatever you want to achieve is to create a separate function in parent component and pass it on to the child component. Call it from the child component when your async code finishes.

Upvotes: 4

T.J. Crowder
T.J. Crowder

Reputation: 1074425

How do I run the parent's componentDidMount() only after the child's asynchronous componentDidMount is resolved ?

If you can possibly avoid this dependency, I would suggest avoiding it. One way to avoid it would be to do the child asynchronous work in the parent, and only render the child when you have all of the child's information (and pass it as props rather than having the child load it).

If for whatever reason you can't do that, you can pass a parent function into the children (as a prop) that they call when they're ready, then have the code in componentDidMount wait until all the children have called back before doing its work.

But again, I'd avoid that complexity.

Upvotes: 4

Related Questions