0

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.

Fahad Farooq
  • 449
  • 5
  • 11
Brahim Oui
  • 29
  • 2
  • 8
  • 1
    When you pass an empty array to `useEffect` it only runs on mount and unmount. Try putting your log statements outside of the `useEffect` method. – Bafsky May 09 '21 at 22:21
  • YEH bro that's the issue, cause the empty array is fired only one in the mount of the component but when adding a dependency it's like on updating, thanks – Brahim Oui May 15 '21 at 13:21

1 Answers1

1

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]);
Fahad Farooq
  • 449
  • 5
  • 11