-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwith-reducer-interceptor.js
More file actions
28 lines (26 loc) · 937 Bytes
/
with-reducer-interceptor.js
File metadata and controls
28 lines (26 loc) · 937 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Add interceptor capabilities to the reducer.
* An interceptor is a function that works exactly as a reducer, but allows for
* both state and action changes. It must return an object with keys { state,
* action }. These new props will be passed to the reducer.
*
* @param {function} reducer The reducer function
* @param {function} interceptor The interceptor function
* @returns function
*/
export function withReducerInterceptor(reducer, interceptor) {
// Sensible default that does nothing.
const intercept =
typeof interceptor === 'function'
? interceptor
: (state, action) => ({ state, action });
return (state, action) => {
const { state: newState, action: newAction } = intercept(state, action);
if (!newAction) {
throw new Error(
`The \`interceptor\` must return an object with keys \`{ action, state }\``
);
}
return reducer(newState, newAction);
};
}