1

I am trying to access the state.X of my store when Redux-watch store.subscribe() is triggered (by updating state.Y), but I can access just initial state values. I am using Redux-toolkit, React-redux, React-watch

When I call the "print" function after I press the UI button, my state is displayed with desired values, but when I call the "print" function in Redux-watch subscribe() function, the state.X has its initial values. Any idea what can be wrong?

Getting state from the store. const date = useSelector((state) => state.calendar);

Print function: const print = () =>{console.log(date);}

Redux-watch subscribe function:

let wData = watch(store.getState, 'calendar.monthData');     
const unsubscribeWData = store.subscribe(wData((newVal, oldVal, objectPath) => 
        {
            if(newVal !== oldVal)
            {
                console.log(newVal); //array with new values
                print(); //state has initial values
            }
               
        }));

Redux-toolkit Slice:

const calendarSlice = createSlice({
    name: "calendar",
    initialState: {
        date: "", //state.X
        monthData: [], //state.Y
    },
    reducers: {
      currentDateAction: (state,action) =>
      {
          const { newDate} = action.payload;
          state.date = newDate;
      }
    },
    extraReducers: builder => {
        builder.addCase(fetchCalendarMonthSum.fulfilled, (state, action) => {
          state.monthData = action.payload;
          })
    }
  });
export const {currentDateAction} = calendarSlice.actions;
export default calendarSlice.reducer;
Jakub Piga
  • 66
  • 5

1 Answers1

0

In the end, I managed to get the state of the store in the subscribe() function by calling directly store.getState().

Though I did not find out why the variable "date" is in the time of the subscribe() method execution set to initial state value, I guess it's something with updating state in the time when the subscribe() function is called. So to get state in the subscribe() method:

let wData = watch(store.getState, 'calendar.monthData');     
const unsubscribeWData = store.subscribe(wData((newVal, oldVal, objectPath) => 
        {
            if(newVal !== oldVal)
            {
                console.log(store.getState().calendar.date)
            }
               
        }));
Jakub Piga
  • 66
  • 5