Ian
Ian

Reputation: 34549

What approach can I use to wait for all child callbacks to complete?

I'm trying to figure out an architecture to allow a parent component, to wait for all the child components to finish rendering and then do some work. Unfortunately in this case I need to do the rendering outside of React and it's done asynchronously instead.

This makes things a little complex. So in my example I want the doSomethingAfterRender() function in the ParentComponent to be called once, after all the ChildComponent customRender calls have completed.

I do have one potential solution, though it doesn't feel very clean which is to use a debounce on the doSomethingAfterRender() function. I'd much rather use a more deterministic approach to only calling this function once if possible.

I'm wondering if anyone has a better suggestion for handling this?

ParentComponent.js

const Parent = (props) => {

    // This is the function I need to call
    const doSomethingAfterRender = useCallback(
        async (params) => {          
             await doSomething();             
        },
    );

    // Extend the child components to provide the doSomethingAfterRender callback down
    const childrenWithProps = React.Children.map(props.children, (child) => {
        if (React.isValidElement(child)) {
            return React.cloneElement(child, { doSomethingAfterRender });
        }

        return child;
    });

    return (
        <React.Fragment>
            <...someDOM....>
            {childrenWithProps}
        </React.Fragment>
    );
   
}

ChildComponent.js (this is actually a HoC)

const withXYZ = (WrappedComponent) =>
    ({ doSomethingAfterRender, ...props }) => {

        // I need to wait for this function to complete, on all child components
        const doRender = useCallback(
            async () => {
                await customRender();

                // Call the doSomething... 
                if (doSomethingAfterRender) {
                    doSomethingAfterRender();
                }
            },
            [doSomethingAfterRender]
        );

        return (
            <React.Fragment>
                <... some DOM ...>
                <WrappedComponent {...props} renderLoop={renderLoop} layer={layer} />
            </React.Fragment>
        );
    };

App.js

const Child = withXYZ(CustomWrappedComponent);

const App = () => {
   return {
      <ParentComponent>
         <Child />
         <Child />
         <Child />
      </ParentComponent>
   };
}

Upvotes: 1

Views: 1176

Answers (1)

iwaduarte
iwaduarte

Reputation: 1698

If I understood correctly. I would do something like: useState with useRef. This way I would trigger only once the Parent and that is when all Child components have finished with their respective async tasks.

Child.js

const child = ({ childRef, updateParent }) => {
  const [text, setText] = useState("Not Set");
   useEffect(() => {
    if (typeof childRef.current !== "boolean") {
      const display = (childRef.current += 1);
      setTimeout(() => {
        setText(`Child Now ${display}`);
          if (childRef.current === 2) {
          updateParent(true);
          childRef.current = false;
        }
      }, 3000);
    }
  }, []);

  return (
    <>
      <div>Test {text}</div>
    </>
  );
}

const Parent = ()=>{
  const childRef = useRef(0);
  const [shouldUpdate, setShouldUpdate] = useState(false);

  useEffect(() => {
    if (shouldUpdate) {
      console.log("updating");
    }
  }, [shouldUpdate]);

  return (
    <div className="App">
      {childRef.current}
      <Child childRef={childRef} updateParent={setShouldUpdate} />
      <Child childRef={childRef} updateParent={setShouldUpdate} />
      <Child childRef={childRef} updateParent={setShouldUpdate} />
    </div>
  );
}

Upvotes: 1

Related Questions