Search code examples
javascriptreactjsreduxreact-reduxredux-toolkit

Is it possible to call a reducer function from another reducer function (within the same slice) using Redux Toolkit?


I have this small module management slice:

const WorkspaceSlice = createSlice({
    name: "workspace",
    initialState: {
        activeModule: null,
        modules:
        {
            ["someModule"]: { ...moduleRenderingData },
        },
    },
    reducers: {
        setActiveModule(state, action)
        {
            state.activeModule = action.payload;
        },
        addModule(state, action)
        {
            const { moduleName, renderingData } = action.payload; 
            if (!state.modules[moduleName])
            {
                state.modules[moduleName] = renderingData;
            }

            // state.activeModule = moduleName; <- basically the same as 'setActiveModule'
            this.setActiveModule(state, action.payload.module); // <- 'this' is undefined
        },
    },
});

export default WorkspaceSlice;

What I'm trying to do is call setActiveModule from within addModule so that I won't have duplicate code, but I get an error because this is undefined.
Is there a way to call one reducer from within another? What's the syntax for that?
If not, is it possible to achieve this functionality in another way, assuming I want to keep both addModule and setActiveModule as separate actions?


Solution

  • The slice object returned from createSlice includes each of the individual case reducer functions you passed in as slice.caseReducers, to help with situations like this.

    So, you could do:

    addModule(state, action) {
        const { moduleName, renderingData } = action.payload; 
        if (!state.modules[moduleName]) {
            state.modules[moduleName] = renderingData;
        }
    
        WorkspacesSlice.caseReducers.setActiveModule(state, action);
    },
    

    Also, reducer functions have no this, because there are no class instances involved. They're just functions.