How to use dispatch in createSlice reducer?

Viewed 8804

For example i have this slice and I want to use dispatch in setUser. How can I do this?

const contactsSlice = createSlice({
  name: 'contacts',
  initialState: initialState,
  reducers: {
    setUsers: (state, { payload }) => {
      // I want to use dispatch here
      dispatch()
    },
    toggleFavorite: (state, { payload }) => {
      //
    },
    toggleCheck: (state, { payload }) => {
      //
    }
  }
})
1 Answers

You can't, you implementing a reducer where dispatch function is not available. Read what reducers are.

Instead, add the logic in React code:

useEffect(() => {
  dispatch(contactsSlice.actions.setUser());
  dispatch(loginSlice.actions.logicAction());
}, []);

Or, add an extra reducer in the target slice.

const contactsSlice = createSlice({
  name: "contacts",
  initialState: initialState,
  reducers: {
    setUsers: (state, { payload }) => {
      // setUsers logic
    },
  },
});

const loginSlice = createSlice({
  name: "login",
  initialState: initialState,
  extraReducers: {
    "contacts/setUsers": (state, { payload }) => {
      // Same logic
    },
  },
});

Or write a middleware, like createAsyncThunk, dispatch and getState functions available under thunkAPI.

Related