how to call an action from another action slice in redux

The solution for “how to call an action from another action slice in redux” can be found here. The following code will assist you in solving the problem.

const counter = createSlice({
name: ‘counter’,
initialState: 0 as number,
reducers: {
increment: (state) => state + 1,
decrement: (state) => state – 1,
multiply: {
reducer: (state, action: PayloadAction) => state * action.payload,
prepare: (value?: number) => ({ payload: value || 2 }), // fallback if the payload is a falsy value
},
},
// “builder callback API”, recommended for TypeScript users
extraReducers: (builder) => {
builder.addCase(incrementBy, (state, action) => {
return state + action.payload
})
builder.addCase(decrementBy, (state, action) => {
return state – action.payload
})
},
})

const user = createSlice({
name: ‘user’,
initialState: { name: ”, age: 20 },
reducers: {
setUserName: (state, action) => {
state.name = action.payload // mutate the state all you want with immer
},
},
// “map object API”
extraReducers: {
// @ts-expect-error in TypeScript, this would need to be [counter.actions.increment.type]
[counter.actions.increment]: (
state,
action /* action will be inferred as “any”, as the map notation does not contain type information */
) => {
state.age += 1
},
},
})

Thank you for using DeclareCode; We hope you were able to resolve the issue.

More questions on [categories-list]

0
inline scripts encapsulated in