Reputation: 108
I'm transitioning from using plain redux to using redux toolkit and I have the following scenario which I can't transition:
plain Redux:
const openEntityScreen = (payload: any) => {
var { module, entity, operation } = payload;
return {
type: `entityScreen/${module}/${entity}/${operation}/open`
}
}
then I have a reducer creator..
export default function (module, entity, operation, initialState) {
return (state, action) => {
switch (action.type) {
case `entityScreen/${module}/${entity}/${operation}/open`: {
...
return {
...state,
...
}
default: return state
}
}
}
which I register like:
var someEntityScreenReducer = createEntityScreenReducer(
'someModuleName',
'someEntityName',
'someOperationName',
someState
);
and then assign this reducer to some part of the state which is responsible for 'someModuleName', 'someEntityName' etc.
basically this way I'm able to quickly create multiple reducers for different modules & entities etc.
So when trying to transition this logic by using redux toolkit there are 2 main problems:
1. I can't build the action's type dynamically using the action's payload.
When using createAction method such as createAction('counter/increment') for example, we need to pass the type explicitly and even if we use the payload prepare callback we still can't build the action's type dynamically.
2. Can't create reducer cases/actions. dynamically
In the above example where we build the cases using the passed reducer creator arguments. I'm not able to achieve this using the createReducer function as there we use pre-build action's to map or to create cases with the builder and I'm also not able to achieve this with createSlice either because over there the cases/actions are created automatically and not dynamically.
Upvotes: 2
Views: 6293
Reputation: 44078
Honestly that sounds as if you are just putting all your component-local UI state into Redux, which we generally advise against. https://redux.js.org/style-guide/style-guide/#evaluate-where-each-piece-of-state-should-live
In most scenarios, Redux slices are pretty distinct from each other. If they are as similar as you describe, you probably can also save all that data in a normalized shape with one single reducer.
All that said, of course you can create higher-order functions to create slices at will. There is an example for that in the documentation that creates a basic slice with additional stuff on top: https://redux-toolkit.js.org/usage/usage-with-typescript#wrapping-createslice
Upvotes: 3