From 31f97672917c6de67960c83eefb6943e03865697 Mon Sep 17 00:00:00 2001 From: Ben Durrant Date: Thu, 26 Sep 2024 12:49:18 +0100 Subject: [PATCH 1/4] Create reduceReducers util --- src/createStore.ts | 2 +- src/index.ts | 2 ++ src/reduceReducers.ts | 59 +++++++++++++++++++++++++++++++++++++ test/reduceReducers.spec.ts | 34 +++++++++++++++++++++ 4 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 src/reduceReducers.ts create mode 100644 test/reduceReducers.spec.ts diff --git a/src/createStore.ts b/src/createStore.ts index 069b9874f7..2612a6be16 100644 --- a/src/createStore.ts +++ b/src/createStore.ts @@ -21,7 +21,7 @@ import { kindOf } from './utils/kindOf' * * @internal */ -type NoInfer = [T][T extends any ? 0 : never] +export type NoInfer = [T][T extends any ? 0 : never] /** * @deprecated diff --git a/src/index.ts b/src/index.ts index 3c12020128..3f6d99120f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ // functions import { createStore, legacy_createStore } from './createStore' import combineReducers from './combineReducers' +import reduceReducers from './reduceReducers' import bindActionCreators from './bindActionCreators' import applyMiddleware from './applyMiddleware' import compose from './compose' @@ -41,6 +42,7 @@ export { createStore, legacy_createStore, combineReducers, + reduceReducers, bindActionCreators, applyMiddleware, compose, diff --git a/src/reduceReducers.ts b/src/reduceReducers.ts new file mode 100644 index 0000000000..a1cdc460e8 --- /dev/null +++ b/src/reduceReducers.ts @@ -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

| undefined, + reducer: Reducer, + ...reducers: { + [K in keyof Actions]: Reducer + } +): Reducer +/** + * 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, + ...reducers: { + [K in keyof Actions]: Reducer + } +): Reducer +export default function reduceReducers( + ...args: [P | S | undefined | Reducer, ...Array>] +): Reducer { + const initialState = + typeof args[0] === 'function' + ? undefined + : (args.shift() as P | S | undefined) + const [firstReducer, ...restReducers] = args as [ + Reducer, + ...Reducer[] + ] + return (state = initialState, action) => + restReducers.reduce( + (state, reducer) => reducer(state, action), + firstReducer(state, action) + ) +} diff --git a/test/reduceReducers.spec.ts b/test/reduceReducers.spec.ts new file mode 100644 index 0000000000..3a8ec659e0 --- /dev/null +++ b/test/reduceReducers.spec.ts @@ -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) + }) + }); +}) \ No newline at end of file From 8729add5361a6ca1fbd411d8724e841ebf3711f1 Mon Sep 17 00:00:00 2001 From: Ben Durrant Date: Fri, 27 Sep 2024 13:22:07 +0100 Subject: [PATCH 2/4] write up docs --- docs/api/reduceReducers.md | 146 +++++++++++++++++++++++++++++++++++++ website/sidebars.js | 1 + 2 files changed, 147 insertions(+) create mode 100644 docs/api/reduceReducers.md diff --git a/docs/api/reduceReducers.md b/docs/api/reduceReducers.md new file mode 100644 index 0000000000..521859c039 --- /dev/null +++ b/docs/api/reduceReducers.md @@ -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_): An 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. diff --git a/website/sidebars.js b/website/sidebars.js index 8ccb21d54c..daa36e14a2 100755 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -152,6 +152,7 @@ module.exports = { 'api/applymiddleware', 'api/bindactioncreators', 'api/compose', + 'api/reducereducers', 'api/utils', { type: 'link', label: 'Error Messages', href: '/errors' } ], From 2d0d0b636b1ea0425fbfe527eb960e41de497f89 Mon Sep 17 00:00:00 2001 From: Ben Durrant Date: Fri, 27 Sep 2024 14:29:07 +0100 Subject: [PATCH 3/4] grammar Co-authored-by: Arya Emami --- docs/api/reduceReducers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/reduceReducers.md b/docs/api/reduceReducers.md index 521859c039..796b9d8698 100644 --- a/docs/api/reduceReducers.md +++ b/docs/api/reduceReducers.md @@ -34,7 +34,7 @@ const rootReducer = reduceReducers( 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_): An set of reducer functions that need to be composed into one. +2. `...reducers` (_Function_): A set of reducer functions that need to be composed into one. ## Returns From 4de400d4f9671a9d2c43d634bb5882cad2d77059 Mon Sep 17 00:00:00 2001 From: Ben Durrant Date: Fri, 27 Sep 2024 14:42:24 +0100 Subject: [PATCH 4/4] Change import Co-authored-by: Arya Emami --- test/reduceReducers.spec.ts | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/test/reduceReducers.spec.ts b/test/reduceReducers.spec.ts index 3a8ec659e0..4214cf9f7b 100644 --- a/test/reduceReducers.spec.ts +++ b/test/reduceReducers.spec.ts @@ -1,34 +1,34 @@ -import reduceReducers from "@internal/reduceReducers"; +import { reduceReducers } from 'redux' describe('Utils', () => { describe('reduceReducers', () => { - const incrementReducer = (state = 0, action: { type: "increment" }) => + const incrementReducer = (state = 0, action: { type: 'increment' }) => action.type === 'increment' ? state + 1 : state - const decrementReducer = (state = 0, action: { type: "decrement" }) => + 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", () => { + 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", () => { + it('accepts an initial state argument', () => { const combined = reduceReducers(2, incrementReducer, decrementReducer) - expect(combined(undefined, { type: "increment" })).toBe(3) + expect(combined(undefined, { type: 'increment' })).toBe(3) }) - it("can accept the preloaded state of the first reducer", () => { + 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) + expect(combined('1', { type: 'increment' })).toBe(2) - const combined2 = reduceReducers("1", parserReducer, incrementReducer) - expect(combined2(undefined, { type: "increment"})).toBe(2) + const combined2 = reduceReducers('1', parserReducer, incrementReducer) + expect(combined2(undefined, { type: 'increment' })).toBe(2) }) - it("accepts undefined as initial state", () => { + it('accepts undefined as initial state', () => { const combined = reduceReducers(undefined, incrementReducer) - expect(combined(undefined, { type: "increment" })).toBe(1) + expect(combined(undefined, { type: 'increment' })).toBe(1) }) - }); -}) \ No newline at end of file + }) +})