https://redux.js.org/tutorials/essentials/part-2-app-structure#redux-slices
How do you implement multiple tabs for a Redux slice that's associated with a component? I have a component that's associated to 1 Redux slice, but now I need to refactor the whole code to insure that each tab of that component is associated with its own slice. So instead of a 1 to 1 relationship, we have a many to many relationship where each tab has its own unique slice. How do you implement it without changing the redux reducers?
One way of doing this is to copy and paste the slice and create slices called editor_1, editor_2, editor_3, etc. and duplicate every action and reducer x number of times, but that's terrible, but the other method requires a lot of breaking changes and is a lot more difficult.
https://codesandbox.io/s/react-redux-todo-list-bnv8y?from-embed=&file=/src/redux/reducers/todos.js
A simple example would be a todo redux store and having to duplicate 10 todo stores on each tab, each tab having its own "store" or "slice" that are independent of one another. What's the best way to go about solving this issue?
CodePudding user response:
You don't need any duplication in your code. Instead use a higher order reducer and a dynamic state shape like:
{
[k: NameSpace]: ITabState;
}
Then create your reducer to select the correct namespace
// Higher level reducer for namespacing
export const MultiReducer = (state = {}, action) => {
if (!action.payload || !action.payload.namespace) {
return state; // Probably something is wrong
}
switch (action.type) {
// Stuff to handle
case actionTypeKeys.DO_A_THING:
return {
...state,
[action.payload.namespace]: {
...singleReducer(state[action.payload.namespace], action),
},
};
default:
return state;
}
};