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 }) => {
//
}
}
})
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.
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.
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 .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With