React warning: Update depth exceeded maximum limit when updating state in useEffect
P粉447785031
P粉447785031 2023-09-06 13:46:55
0
1
559

I'm trying to update my state variable which is an object containing a boolean variable. Once the data is available (in response to an API call invoked on button click), I update my state inside useEffect. Then with this data I call another component, a modal, and if no data is available, I show another modal. When I close the popup, the state variable should be updated.

const [modalState, setModalState] = useState<IModalState>({
  showNoUsersModal: false,
  showModal: false,
});

useEffect(() => {
  if (data && data.length > 0) {
    setModalState({
      ...modalState,
      showModal: true,
      showNoUsersModal: false,
    });
  } else if (data && data.length === 0) {
    setModalState({
      ...modalState,
      showModal: false,
      showNoUsersModal: true,
    });
  }
});

const onApplicationSuccess = () => {
  setModalState({
    ...modalState,
    showModal: false,
    showNoUsersModal: false,
  });
}

const onClose = () => {
  setModalState({
    ...modalState,
    showModal: false,
    showNoUsersModal: false,
  });
}

return (
  <div>
    {modalState.showNoUsersModal && (
      <NoUsersFoundModal
        onCancel={() =>
          setModalState({
            ...modalState,
            showModal: false,
            showNoUsersModal: false,
          })
        }
      />
    )}

    {modalState.showModal && (
      <SomeOtherModal
        onCancel={() =>
          setModalState({
            ...modalState,
            showModal: false,
            showNoUsersModal: false,
          })
        }
      />
    )}
  </div>
)
P粉447785031
P粉447785031

reply all(1)
P粉163465905

This issue was because you didn't pass any dependency array to useEffect so when ever state was changing useEffect was calling again. here is the solution .

useEffect(() => {
    if (data && data.length > 0 ) {
      setModalState({
        ...modalState,
        showModal: true,
        showNoUsersModal: false,
      });
    } else if (data && data.length == 0) {
      setModalState({
        ...modalState,
        showModal: false,
        showNoUsersModal: true,
      });
    }
  },[]);

The problem is because you don't pass any dependency array to useEffect, so useEffect will be called again every time the state changes. Here is the solution.

useEffect(() => {
    if (data && data.length > 0 ) {
      setModalState({
        ...modalState,
        showModal: true,
        showNoUsersModal: false,
      });
    } else if (data && data.length == 0) {
      setModalState({
        ...modalState,
        showModal: false,
        showNoUsersModal: true,
      });
    }
  },[]);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template