'useEffect infinite loop with redux toolkit dispatch and fetch

I'm using redux-toolkit in react, i have a loading state for the entire app. In a component I'm doing a function to dispatch the loading to true then fetch data then dispatch loading to false. Then putting that function in a useEffect. Here's the code:

const getUsers = async () => {
      try {
      dispatch(setLoading(true));
      const req = await axios.get(URL);
      const res = req.data;
      setUsers(res);
      dispatch(setLoading(false));
      console.log("data fetched");
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    getUsers();
  }, []);

The problem is that the useEffect is running infinitely non-stop.

  • If i remove the 2nd dispatch in the function(dispatch(setLoading(false))), it works and useEffect runs once. or even if i keep the 1st dispatch and keep the 2nd it also works.
  • If i remove the data fetching and just keep the two dispatch, it works.

why is this happening? at first i thought it's because running two dispatch but then it seems related to combining fetching with these. I do this in basic redux and never faced a problem like this one.



Solution 1:[1]

Turns out the problem isn't with redux-toolkit but a mistake i've made with react-router v6.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AhmadBenos