Skip to content

Commit 5d8415d

Browse files
authored
2520 collection item reducer (#3550)
1 parent 78716bf commit 5d8415d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

docs/recipes/structuring-reducers/ReusingReducerLogic.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,42 @@ const rootReducer = combineReducers({
138138
These basic patterns allow you to do things like having multiple instances of a smart connected component within the UI, or reuse common logic for generic capabilities such as pagination or sorting.
139139
140140
In addition to generating reducers this way, you might also want to generate action creators using the same approach, and could generate them both at the same time with helper functions. See [Action/Reducer Generators](https://github.com/markerikson/redux-ecosystem-links/blob/master/action-reducer-generators.md) and [Reducers](https://github.com/markerikson/redux-ecosystem-links/blob/master/reducers.md) libraries for action/reducer utilities.
141+
142+
## Collection / Item Reducer Pattern
143+
144+
This pattern allows you to have multiple states and use a common reducer to update each state based on an additional parameter inside the action object.
145+
146+
```js
147+
function counterReducer(state, action) {
148+
switch(action.type) {
149+
case "INCREMENT" : return state + 1;
150+
case "DECREMENT" : return state - 1;
151+
}
152+
}
153+
154+
function countersArrayReducer(state, action) {
155+
switch(action.type) {
156+
case "INCREMENT":
157+
case "DECREMENT":
158+
return state.map( (counter, index) => {
159+
if(index !== action.index) return counter;
160+
return counterReducer(counter, action);
161+
});
162+
default:
163+
return state;
164+
}
165+
}
166+
167+
function countersMapReducer(state, action) {
168+
switch(action.type) {
169+
case "INCREMENT":
170+
case "DECREMENT":
171+
return {
172+
...state,
173+
state[action.name] : counterReducer(state[action.name], action)
174+
};
175+
default:
176+
return state;
177+
}
178+
}
179+
```

0 commit comments

Comments
 (0)