1 | /**
|
2 | @license
|
3 | Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
|
4 | This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
|
5 | The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
|
6 | The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
|
7 | Code distributed by Google as part of the polymer project is also
|
8 | subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
|
9 | */
|
10 |
|
11 | import { ReducersMapObject, StoreEnhancer } from 'redux'
|
12 |
|
13 | export interface LazyStore {
|
14 | addReducers: (newReducers: ReducersMapObject) => void
|
15 | }
|
16 |
|
17 | /**
|
18 | A Redux store enhancer that lets you lazy-install reducers after the store
|
19 | has booted up. Use this if your application lazy-loads routes that are connected
|
20 | to a Redux store.
|
21 |
|
22 | Example:
|
23 |
|
24 | import { combineReducers } from 'redux';
|
25 | import { lazyReducerEnhancer } from 'pwa-helpers/lazy-reducer-enhancer.js';
|
26 | import someReducer from './reducers/someReducer.js';
|
27 |
|
28 | export const store = createStore(
|
29 | (state, action) => state,
|
30 | compose(lazyReducerEnhancer(combineReducers))
|
31 | );
|
32 |
|
33 | Then, in your page/element, you can lazy load a specific reducer with:
|
34 |
|
35 | store.addReducers({
|
36 | someReducer
|
37 | });
|
38 | */
|
39 | export const lazyReducerEnhancer =
|
40 | (combineReducers: typeof import('redux').combineReducers) => {
|
41 | const enhancer: StoreEnhancer<LazyStore> = (nextCreator) => {
|
42 | return (origReducer, preloadedState) => {
|
43 | let lazyReducers = {};
|
44 | const nextStore = nextCreator(origReducer, preloadedState);
|
45 | return {
|
46 | ...nextStore,
|
47 | addReducers(newReducers) {
|
48 | const combinedReducerMap: ReducersMapObject = {
|
49 | ...lazyReducers,
|
50 | ...newReducers
|
51 | };
|
52 |
|
53 | this.replaceReducer(combineReducers(lazyReducers = combinedReducerMap));
|
54 | }
|
55 | }
|
56 | }
|
57 | }
|
58 |
|
59 | return enhancer;
|
60 | };
|