Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 387
tys Avatar asked Oct 16 '25 02:10

tys


2 Answers

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.

like image 160
T.J. Crowder Avatar answered Oct 18 '25 19:10

T.J. Crowder


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.

like image 36
vatz88 Avatar answered Oct 18 '25 19:10

vatz88