简体   繁体   中英

setState using its callback inside useEffect causing infinite looping

I know this is an over asked question regarding useEffect and useState infinite loops. I have read almost every question about it and also searched over the internet in order to try to fix it before posting here. The most recent article that I read was this one .

Before I read the article my useState function inside useEffect was without the useState 's callback, so it was what I thought which was causing the problem. But after moving it from this:

setNotifications({
  ...notifications,
  [type]: {
    ...notifications[type],
    active: portfolioSettings[type],
    payload: {
      ...notifications[type].payload,
      [pKey]: portfolioSettings[pKey],
    },
  },
});

to this:

setNotifications((currState) => ({
  ...currState,
  [type]: {
    ...currState[type],
    active: portfolioSettings[type],
    payload: {
      ...currState[type].payload,
      [pKey]: portfolioSettings[pKey],
    },
  },
}));

Unfortunately the infinite loop persists. Here are all useEffect functions (the last one is the one causing the infinite looping) that I'm using in this component.

// Set default selected portfolio to the active portfolio
useEffect(() => {
  let mounted = true;

  const setPortfolioData = () => {
    if (activePortfolio) {
      const portfolioId = activePortfolio.id;
      const portfolioName = activePortfolio.name;
      setSelectedPortfolio({
        portfolioId,
        portfolioName,
      });
    }
  };

  if (mounted) setPortfolioData();

  return () => {
    mounted = false;
  };
}, [activePortfolio]);

// Set all the categories if no category is set
useEffect(() => {
  let mounted = true;

  if (mounted && allCvmCategories) {
    const allCvmCategoriesNames = allCvmCategories.map((c) => c);
    setNotifications((currState) => ({
      ...currState,
      isCvmNotificationEnabled: {
        ...currState.isCvmNotificationEnabled,
        payload: {
          ...currState.isCvmNotificationEnabled.payload,
          cvmCategories: allCvmCategoriesNames,
        },
      },
    }));
    setIsCvmCategoriesReady(true);
  }

  return () => {
    mounted = false;
  };
}, [allCvmCategories]);

// THE ONE WHICH IS CAUSING INFINITE LOOPING
// THE notificationsTypes AND notificationsInitialState
// ARE DECLARED IN THE ROOT OF THE JSX FILE
// OUT OF THE FUNCTIONAL COMPONENT
useEffect(() => {
  let mounted = true;

  if (
    mounted &&
    isCvmCategoriesReady &&
    allPortfolios &&
    selectedPortfolio.portfolioId
  ) {
    const { portfolioId } = selectedPortfolio;
    const portfolioSettings = allPortfolios[portfolioId].settings;

    if (portfolioSettings) {
      notificationsTypes.forEach((type) => {
        if (Object.prototype.hasOwnProperty.call(portfolioSettings, type)) {
          const { payloadKeys } = notificationsInitialState[type];
          if (payloadKeys.length > 0) {
            payloadKeys.forEach((pKey) => {
              if (
                Object.prototype.hasOwnProperty.call(portfolioSettings, pKey)
              ) {
                setNotifications((currState) => ({
                  ...currState,
                  [type]: {
                    ...currState[type],
                    active: portfolioSettings[type],
                    payload: {
                      ...currState[type].payload,
                      [pKey]: portfolioSettings[pKey],
                    },
                  },
                }));
              }
            });
          } else {
            setNotifications((currState) => ({
              ...currState,
              [type]: {
                ...currState[type],
                active: portfolioSettings[type],
              },
            }));
          }
        }
      });
    }
  }

  return () => {
    mounted = false;
  };
}, [allPortfolios, isCvmCategoriesReady, selectedPortfolio]);

Thanks for the responses. I have found the problem, it was with the hook that I was using (SWR) for fetching. Making the allPortfolios change all the time. I have fixed it wrapping into a new custom hook.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM