0

I am trying to create load more functionality by fetching only the necessary date i.e. the next one that needs to be added to the existing state that I have in the redux store, but I have a problem my redux actions are duplicated.

Component App.js

function App() {
  const dispatch = useDispatch();
  const data = useSelector(questionsData);

  useEffect(() => {
    const fetchQuestions = async () => {
      dispatch(fetchQuestionsBegin());
      try {
        const { data } = await mainUrl(`/questions?last=5`);
        return dispatch(fetchQuestionsSuccess(data));
      } catch (err) {
        return dispatch(fetchQuestionsFailure());
      }
    };
    fetchQuestions();
  }, [dispatch]);

  return (
    <>
      <div>TEST</div>
    </>
  );
}

creating store

const store = configureStore({
  reducer: {
    questionsStore: questionsReducer,
  },
});

export default store;

slice

const initialState = {
  loading: false,
  questions: [],
  error: "",
};

const questionsSlice = createSlice({
  name: "questions",
  initialState,
  reducers: {
    fetchQuestionsBegin(state) {
      return { ...state, loading: true, error: "" };
    },
    fetchQuestionsSuccess(state, action) {
      return {
        ...state,
        loading: false,
        questions: [...state.questions, ...action.payload],
      };
    },
    fetchQuestionsFailure(state, action) {
      return { ...state, loading: false, error: action.payload };
    },
  },
});

export const { reducer: questionsReducer, actions } = questionsSlice;

export const {
  fetchQuestionsBegin,
  fetchQuestionsSuccess,
  fetchQuestionsFailure,
} = actions;

redux

When I exclude <React.StrictMode> everything works fine.

Erol
  • 11
  • 1

1 Answers1

0

Refer to link. Strict mode can cause multiple methods to invoke multiple times. Its most likely that your redux is ran twice when the component mounts for the first time. You can implement useRef to detect initial mount and then conditionally render after

  const isMounted = useRef(false)
  useEffect(() => {
    isMounted.current = true;
  }, [])


  useEffect(() => {
    if (isMounted.current) {
       const fetchQuestions = async () => {
         dispatch(fetchQuestionsBegin());
         try {
           const { data } = await mainUrl(`/questions?last=5`);
           return dispatch(fetchQuestionsSuccess(data));
         } catch (err) {
           return dispatch(fetchQuestionsFailure());
         }
       };
       fetchQuestions();
    }
  }, [dispatch]);

benwl
  • 366
  • 2
  • 17