useEffect / dispatch multiple network calls

49 Views Asked by At
useEffect(() => {
    function initDashboardData() {
      console.count("initDashboardData");
      void dispatch(getDatabasesList());
      void dispatch(getUserConfig());
      void dispatch(
        getHistoricalData({ startTimestamp: getDateXDaysAgo(14, new Date()), endTimestamp: new Date() })
      );
    }

    void initDashboardData();
  }, [dispatch]);

All the actions (getDatabasesList, getUserConfig, etc..) are Redux createAsyncThunk actions that call an API.

When the component renders this function is called around five times, create 5 network calls.

How do you prevent multiple network calls from happening using dispatch w/ useEffect?

1

There are 1 best solutions below

0
Greg Motyl On

To prevent multiple calls of the function you could use a useRef hook's help, like so:

const dataLoadedFlag = useRef(false);

useEffect(() => {
    function initDashboardData() {
      // dispatch your stuff...
      dataLoadedFlag.current = true;
    }

    if (!dataLoadedFlag.current) {
      initDashboardData();
    }
  }, [dispatch]);