-
-
Notifications
You must be signed in to change notification settings - Fork 15.2k
Create reduceReducers util #4744
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
EskiMojo14
wants to merge
4
commits into
master
Choose a base branch
from
reduce-reducers
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+243
−1
Open
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
--- | ||
id: reducereducers | ||
title: reduceReducers | ||
hide_title: true | ||
description: 'API > reduceReducers: running multiple reducers on the same state' | ||
--- | ||
|
||
| ||
|
||
# `reduceReducers(initialState, ...reducers)` | ||
|
||
## Overview | ||
|
||
The `reduceReducers` helper function composes multiple reducer functions into one. It runs each reducer in sequence, passing the result of each to the next, and returns the final result. | ||
|
||
For example, you might want a base reducer built using [`combineReducers`](./combineReducers), but then also include some logic that requires the full combined state. | ||
|
||
```js | ||
const combinedReducer = combineReducers({ | ||
counter: counterReducer, | ||
todos: todosReducer | ||
}) | ||
|
||
const rootReducer = reduceReducers(combinedReducer, otherTopLevelFeatureReducer) | ||
// or | ||
const rootReducer = reduceReducers( | ||
{ counter: 0, todos: [] }, | ||
combinedReducer, | ||
otherTopLevelFeatureReducer | ||
) | ||
``` | ||
|
||
## Arguments | ||
|
||
1. `initialState` (_any_): The initial state. This can also be the preloaded state for the reducer. This can also be omitted, and the first reducer's initial state will be used instead. | ||
|
||
2. `...reducers` (_Function_): A set of reducer functions that need to be composed into one. | ||
|
||
## Returns | ||
|
||
(_Function_): A reducer that invokes every reducer passed in order, and returns the result of the last reducer. | ||
|
||
## Example | ||
|
||
#### `reducers/todos.js` | ||
|
||
```js | ||
export default function todos(state = [], action) { | ||
switch (action.type) { | ||
case 'ADD_TODO': | ||
return state.concat([action.text]) | ||
default: | ||
return state | ||
} | ||
} | ||
``` | ||
|
||
#### `reducers/counter.js` | ||
|
||
```js | ||
export default function counter(state = 0, action) { | ||
switch (action.type) { | ||
case 'INCREMENT': | ||
return state + 1 | ||
case 'DECREMENT': | ||
return state - 1 | ||
default: | ||
return state | ||
} | ||
} | ||
``` | ||
|
||
#### `reducers/otherTopLevelFeature.js` | ||
|
||
```js | ||
export default function otherTopLevelFeature( | ||
state = { counter: 0, todos: [] }, | ||
action | ||
) { | ||
switch (action.type) { | ||
case 'COUNT_TODOS': | ||
return { | ||
...state, | ||
counter: state.todos.length | ||
} | ||
default: | ||
return state | ||
} | ||
} | ||
``` | ||
|
||
#### `reducers/index.js` | ||
|
||
```js | ||
import { combineReducers, reduceReducers } from '@reduxjs/toolkit' | ||
import todos from './todos' | ||
import counter from './counter' | ||
import otherTopLevelFeature from './otherTopLevelFeature' | ||
|
||
export default reduceReducers( | ||
combineReducers({ | ||
counter, | ||
todos | ||
}), | ||
otherTopLevelFeature | ||
) | ||
``` | ||
|
||
#### `App.js` | ||
|
||
```js | ||
import { configureStore } from '@reduxjs/toolkit' | ||
import reducer from './reducers/index' | ||
|
||
const store = configureStore({ | ||
reducer | ||
}) | ||
console.log(store.getState()) | ||
// { | ||
// counter: 0, | ||
// todos: [] | ||
// } | ||
|
||
store.dispatch({ | ||
type: 'ADD_TODO', | ||
text: 'Use Redux' | ||
}) | ||
console.log(store.getState()) | ||
// { | ||
// counter: 0, | ||
// todos: [ 'Use Redux' ] | ||
// } | ||
|
||
store.dispatch({ | ||
type: 'COUNT_TODOS' | ||
}) | ||
console.log(store.getState()) | ||
// { | ||
// counter: 1, | ||
// todos: [ 'Use Redux' ] | ||
// } | ||
``` | ||
|
||
## Tips | ||
|
||
- You may call `reduceReducers` at any level of the reducer hierarchy. It doesn't have to happen at the top. In fact you may use it again to split the child reducers that get too complicated into independent grandchildren, and so on. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import type { NoInfer } from './createStore' | ||
import type { Action } from './types/actions' | ||
import type { Reducer } from './types/reducers' | ||
|
||
/** | ||
* Composes multiple reducers into one. | ||
* | ||
* @param initialState The initial state, which can be a different preloaded state. | ||
* @param reducer The first reducer. Can accept a different preloaded state. | ||
* @param reducers The rest of the reducers. | ||
* @returns A reducer function that invokes every reducer passed in order, and returns the result of the last reducer. | ||
*/ | ||
export default function reduceReducers< | ||
S, | ||
A extends Action, | ||
Actions extends Action[], | ||
P | ||
>( | ||
initialState: NoInfer<P | S> | undefined, | ||
reducer: Reducer<S, A, P>, | ||
...reducers: { | ||
[K in keyof Actions]: Reducer<S, Actions[K]> | ||
} | ||
): Reducer<S, A | Actions[number], P> | ||
/** | ||
* Composes multiple reducers into one. | ||
* | ||
* @param reducer The first reducer. Can accept a different preloaded state. | ||
* @param reducers The rest of the reducers. | ||
* @returns A reducer function that invokes every reducer passed in order, and returns the result of the last reducer. | ||
*/ | ||
export default function reduceReducers< | ||
S, | ||
A extends Action, | ||
Actions extends Action[], | ||
P | ||
>( | ||
reducer: Reducer<S, A, P>, | ||
...reducers: { | ||
[K in keyof Actions]: Reducer<S, Actions[K]> | ||
} | ||
): Reducer<S, A | Actions[number], P> | ||
export default function reduceReducers<S, A extends Action, P>( | ||
...args: [P | S | undefined | Reducer<S, A, P>, ...Array<Reducer<S, A>>] | ||
): Reducer<S, A, P> { | ||
const initialState = | ||
typeof args[0] === 'function' | ||
? undefined | ||
: (args.shift() as P | S | undefined) | ||
const [firstReducer, ...restReducers] = args as [ | ||
Reducer<S, A, P>, | ||
...Reducer<S, A>[] | ||
] | ||
return (state = initialState, action) => | ||
restReducers.reduce( | ||
(state, reducer) => reducer(state, action), | ||
firstReducer(state, action) | ||
) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import reduceReducers from "@internal/reduceReducers"; | ||
|
||
describe('Utils', () => { | ||
describe('reduceReducers', () => { | ||
const incrementReducer = (state = 0, action: { type: "increment" }) => | ||
action.type === 'increment' ? state + 1 : state | ||
const decrementReducer = (state = 0, action: { type: "decrement" }) => | ||
action.type === 'decrement' ? state - 1 : state | ||
|
||
it("runs multiple reducers in sequence and returns the result of the last one", () => { | ||
const combined = reduceReducers(incrementReducer, decrementReducer) | ||
expect(combined(0, { type: 'increment' })).toBe(1) | ||
expect(combined(1, { type: 'decrement' })).toBe(0) | ||
}) | ||
it("accepts an initial state argument", () => { | ||
const combined = reduceReducers(2, incrementReducer, decrementReducer) | ||
expect(combined(undefined, { type: "increment" })).toBe(3) | ||
}) | ||
it("can accept the preloaded state of the first reducer", () => { | ||
const parserReducer = (state: number | string = 0) => | ||
typeof state === 'string' ? parseInt(state, 10) : state | ||
|
||
const combined = reduceReducers(parserReducer, incrementReducer) | ||
expect(combined("1", { type: "increment"})).toBe(2) | ||
|
||
const combined2 = reduceReducers("1", parserReducer, incrementReducer) | ||
expect(combined2(undefined, { type: "increment"})).toBe(2) | ||
}) | ||
it("accepts undefined as initial state", () => { | ||
const combined = reduceReducers(undefined, incrementReducer) | ||
expect(combined(undefined, { type: "increment" })).toBe(1) | ||
}) | ||
}); | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.