I have a createSnapshot reducer that will store snapshots of a portion of a slice as the state is being mutated. I have 30+ reducers for the slice. Rather than adding caseReducers.createSnapshot at the end of every reducer, is there a cleaner way to achieve this, like a middleware reducer?
Asked
Active
Viewed 100 times
2 Answers
0
You can create a higher order reducer, that is a function taking a reducer as an argument and returning a new reducer, for instance (untested):
const withSnapshot = reducer => (state, action) => {
// Call the original reducer
const tmpState = reducer(state, action);
// Create the snapshot
const finalState = createSnapshot(tmpState);
// Return the state
return finalState;
}
and then in your configureStore
you do something as follows:
mySlice: withSnapshot(mySliceReducer),

Guillaume Brunerie
- 4,676
- 3
- 24
- 32
0
.addMatcher allows listening to multiple reducers input
extraReducers(builder) {
builder
.addMatcher(isAnyOf(reducer1, reducer2),(state,action)=>{
// Do something
})
}

Eric P
- 29
- 7