2

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 ?

t.c
  • 623
  • 5
  • 19
  • pass the child async method from the parent and called from the parent componentDidMount() method in that way once your child async call finished you have control in parent – Dhaval Patel Aug 09 '19 at 13:03

2 Answers2

4

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
vatz88
  • 2,422
  • 2
  • 14
  • 25
3

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875