Home > Enterprise >  Replacing a whole array in React Redux - calling a dispatch function without infinite loop
Replacing a whole array in React Redux - calling a dispatch function without infinite loop

Time:01-10

I am relatively new to Redux. I have the following action -

import { createSlice } from "@reduxjs/toolkit";

export const currentListSlice = createSlice({
  name: "currentList",
  initialState: [1, 2, 3],

  reducers: {
    setCurrentList: (state, action) => {
      return action.payload;
    },
  },
});

export const { setCurrentList } = currentListSlice.actions;

export default currentListSlice.reducer;

The initialState:[1,2,3] is for development only - The initialState will be empty and will be updated with a function that will use data from firebase.

Next, I'm calling the array and rendering a card from each object, using the numbers in the state to get the rest of the info from the data objects.

const preList = useSelector((state) => state.currentList);
  const list = [];
  preList.map((item) => list.push(DATA[item]));

list is being used as the data in a Flatlist. So far so good.

Then I am calling the function to update currentList on redux like this -

useEffect(() => {
    dispatch(setCurrentList(fiveRandomBeaches(DATA.length)));
  }, [preList]);

I am going into an infinite loop.

To test, I added a button and called the dispatch with onPress event and the function works just fine, so no issues with the function.

dispatch(setCurrentList(fiveRandomBeaches(DATA.length)))

How do I call the dispatch function here without getting the infinite loop? Thanks

I really don't think the fiveRandomBeaches function is relevant to the issue but here goes

export const fiveRandomBeaches = (dataLength) => {
  let beachesList = [];
  let uniqueBeachesList;
  let rndBeach;

  do {
    rndMarker = Math.floor(Math.random() * dataLength);
    beachesList.push(rndMarker);
    uniqueBeachesList = [...new Set(beachesList)];
  } while (uniqueBeachesList.length < 5);
  return uniqueBeachesList;
};

CodePudding user response:

Your useEffect has a dependency on preList and that is causing the infinite loop. setCurrentList will update it and cause the effect to run again ad infinitum. Removing preList from the dependency array should solve your problem.

  • Related