0

I would like to give additional parameters for Dependency Injection to Reducer.

When I created the Store, I added Arguments like this.

export default configureStore({
  reducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      thunk: { extraArgument: { service } },
    }).concat(logger),
  devTools: true,
});

I know how to use it in createAsyncThunk function, but I don't know how to use it in other Reducer. There is no third parameter.

In the following case, there is no third factor.

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    logout: (state, action, third) => {

      // third is undefiend!!! it doesn't get value.
      // but createAsyncThunk does

      const { extra} = third;
      const { service } = extra;
      service.authService.logout();
      return {
        isLoggedIn: false,
        userId: null,
        profile: {
          name: null,
        },
        token: null,
      };
    }
  },

1 Answers1

1

Something like your service.authService.logout(); is a side effect and side effects are never allowed in a Redux reducer. A reducer is only allowed to read state and action and (in the case of createSlice) modify state. No other side effects are allowed. So nothing like this will be available in your reducers.

You could be using the listener middleware for this though.

listenerMiddleware.startListening({
  actionCreator: authSlice.actions.logout,
  effect: async (action, listenerApi) => {
    listenerApi.extra.authService.logout()
  },
})
phry
  • 35,762
  • 5
  • 67
  • 81
  • I understand! Thank you. To maintain the pure function reducer, I modified the service caller to "redux-thunks". – nerdchanii Jun 08 '22 at 23:33