简体   繁体   中英

How to use single action type in different reducer function with createSlice method in redux-toolkit

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.

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'
      })
    }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM