Home > Mobile >  redux toolkit dipatching buildercase twice actions
redux toolkit dipatching buildercase twice actions

Time:01-15

I am trying to figure out why during refresh does the dispatch action gets run twice and the endpoint is also been called twice.

This is my slice

extraReducers: (builder) => {
    builder.addCase(fetchAppointments.pending, (state, action) => {
      state.loading = true;
    });
    builder.addCase(fetchAppointments.fulfilled, (state, {payload}) => {
      state.loading = false;
      state.total = payload.total;
      state.dates = payload.dates;
      state.data = payload.data;
    });
    builder.addCase(fetchAppointments.rejected, (state, action) => {
      state.loading = false;
      state.total = {};
      state.dates = [];
      state.data = {};
    });
  },

In my component I have it set up this way

  const { apptDates } = useSelector<AppState>((state: any) => {
    return {
      apptDates: state.appt
    }
  });

  useEffect(() => {
    dispatch(fetchAppointments());
  }, [dispatch]);

Any ideas as to why the dispatch are called twice and the endpoint is call called twice in the network tab?

CodePudding user response:

If you have React's <StrictMode> component in use, all useEffect will run twice in development mode. That's probably what is happening here.

CodePudding user response:

There could be a few reasons why the dispatch action is getting called twice and the endpoint is also being called twice:

  1. One potential cause could be that the component containing your useEffect hook is re-rendering multiple times. This could be caused by a parent component re-rendering, or by a variable in the component's state or props changing.
  2. Another potential cause could be that the dispatch(fetchAppointments()) function is being called multiple times. This could be caused by an event handler or other function calling it multiple times, or by a bug in your code.
  3. Another cause of the issue could be that the useEffect is in a loop or a re-rendering component.

I suggest you to use the React Developer Tools to inspect your component and see if it is re-rendering multiple times, or if the function is being called multiple times. Additionally, you could add some console.log statements to your code to trace when the function is being called, and to see if it is being called multiple times.

  • Related