Search code examples
reactjsreact-hooksreact-contextreact-functional-componentreact-lifecycle

The issue of React Lifecycle in a Functional Component (Data undefined in the child component)


I ran into a problem when I try to call backend api from a parent component the call result is always null in the child component. Here is my implementation: The parent component:

const Parent = () => {
  const { loadFiData, fiData, year } = useContext(DashboardContext);

  useEffect(() => {
    let loading = true;
    
    if (loading) loadFiData();

    return () => (loading = false);
  }, [year]);

  return (
    <div className="mt-5">
      <Child />
    </div>
  );
};

Child Component:

const Chart1 = () => {
  const { fiData } = useContext(DashboardContext);

  useEffect(() => {
    if (fiData) {
      console.log('there is a data');
    } else {
      console.log('there is no data');
    }
  }, []);

  return (
    <h1>Child</h1>
  );
};

so I look for a way to execute the function that calls the backend from the parent component first so the child can access to the data.


Solution

  • Add fiData as a dependency of useEffect in Chart1/Child component. Then the code inside the useEffect should run 2 times. It should first console there is no data and when the request completes inside the context, then it should console there is a data.

    useEffect(() => {
        if (fiData) {
            console.log('there is a data');
        } else {
            console.log('there is no data');
        }
    }, [fiData]);