Reputation: 185
Is it possible that multiple reducer (which is created with createSlice method) must respond to the same action?
import { createSlice } from '@reduxjs/toolkit';
const isAuthenticated = createSlice({
name: 'isAuthenticated',
initialState: false,
reducers: {
loginSuccess(state, action) {
return true;
},
logout(state, action) {
return false;
},
},
});
export const { loginSuccess, logout } = isAuthenticated.actions;
export default isAuthenticated.reducer;
const currentUser = createSlice({
name: 'currenUser',
initialState: 'jhon',
reducers: {
loginSuccess(state, action) {
return 'steve';
},
logout() {
return state;
},
},
});
export const currentUserReducer = currentUser.reducer;
As You can see action.type loginSuccess is in two different reducers since i am only exporting loginSuccess of isAuthenticated i can use only that action to dispatch. i know i can export loginSuccess from currentUser as well but i want to dispatch only one action and change the state in two different states.
I know this can be done with vanilla redux and also redux recommend using it Here
In short i am trying to replicate this but with createSlice method in redux-tool-kit.
Thanks in advance for helping.
Upvotes: 1
Views: 991
Reputation: 44078
You are looking for extraReducers:
const isAuthenticated = createSlice({
name: 'isAuthenticated',
initialState: false,
reducers: {
loginSuccess(state, action) {
return true;
},
logout(state, action) {
return false;
},
},
});
export const { loginSuccess, logout } = isAuthenticated.actions;
export default isAuthenticated.reducer;
const currentUser = createSlice({
name: 'currenUser',
initialState: 'jhon',
reducers: {
logout() {
return state;
},
},
extraReducers: builder => {
builder.addCase(isAuthenticated.actions.loginSuccess, () => {
return 'steve'
})
}
});
Upvotes: 2