Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dispatch in createSlice reducer?

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 }) => {
      //
    }
  }
})
like image 675
Nick Avatar asked May 16 '20 08:05

Nick


People also ask

Can we use dispatch in reducer?

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

How do I make an API call using createSlice?

import { createSlice } from "@reduxjs/toolkit"; export const slice = createSlice({ name: "login", initialState: { email: "", password: "", user: null, token: null }, reducers: { login: (state, action) => { console. log(action. payload.

What is the input for the dispatch function?

The dispatch function is in the same scope as the current state of the app. So that means that inside the dispatch function, we have access to an object called currentState that is the current state in our app. In that same scope is the reducer function that we have written and passed into createStore or useReducer .


Video Answer


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.

like image 89
Dennis Vash Avatar answered Oct 24 '22 18:10

Dennis Vash