Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine top-level reducer with slice reducers, for RTK.configureStore

How can combine top-level reducer code with the aggregate reducer from combineReducers?

I have defined several store slices. combineReducers allows creating a single reducer, by mapping a name to each slice's reducer:

import { slice as fooSlice } from './foo/slices.js'
import { slice as barSlice } from './bar/slices.js'

export const store = RTK.configureStore({
    reducer: {
        foo: fooSlice.reducer,
        bar: barSlice.reducer,
    },
})

Each of those reducers can, by design of createSlice, only access their own subset of the state.

Then, I need some top-level reducer code as well. For example, a “save to persistent storage” action:

import {
    persistenceActions,
    saveWorldState,
} from './persistence.js'


function globalStoreReducer(state, action) {
    switch (action.type) {
        [persistenceActions.save]: {
            saveWorldState(state)
        },
    default:
        // FIXME: How to delegate to the slice reducers?
        return reducer(state, action)
    }
    return state
}

The goal is to have a single reducer function that combines not only all the slice reducers, but also the top-level reducer with access to the entire store. Then, use that for RTK.configureStore:

export const store = RTK.configureStore({
    reducer: globalStoreReducer,
})

How can I properly combine the directly-implemented reducer code with the combined reducer, for use as the single reducer in RTK.configureStore?

like image 513
bignose Avatar asked Dec 18 '25 19:12

bignose


1 Answers

You would do a

const allMySliceReducersReducer = combineReducers({
        foo: fooSlice.reducer,
        bar: barSlice.reducer,
    })

and call that from your globalStoreReducer.

But that said, saveWorldState sounds like a side effect, and those are never allowed in reducers.

like image 133
phry Avatar answered Dec 22 '25 12:12

phry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!