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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply