-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathstore-persist.js
63 lines (55 loc) · 1.68 KB
/
store-persist.js
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* Internal dependencies
*/
const DEFAULT_STORAGE_KEY = 'REDUX_PERSIST';
/**
* Store enhancer to persist a specified reducer key
* @param {Object} options Options object
* @param {String} options.reducerKey The reducer key to persist
* @param {String} options.storageKey The storage key to use
* @param {Object} options.defaults Default values of the reducer key
*
* @return {Function} Store enhancer
*/
export default function storePersist( {
reducerKey,
storageKey = DEFAULT_STORAGE_KEY,
defaults = {},
} ) {
return ( createStore ) => ( reducer, preloadedState, enhancer ) => {
// EnhancedReducer with auto-rehydration
const enhancedReducer = ( state, action ) => {
const nextState = reducer( state, action );
if ( action.type === 'REDUX_REHYDRATE' ) {
return {
...nextState,
[ reducerKey ]: action.payload,
};
}
return nextState;
};
const store = createStore( enhancedReducer, preloadedState, enhancer );
// Load initially persisted value
const persistedString = window.localStorage.getItem( storageKey );
if ( persistedString ) {
const persistedState = {
...defaults,
...JSON.parse( persistedString ),
};
store.dispatch( {
type: 'REDUX_REHYDRATE',
payload: persistedState,
} );
}
// Persist updated preferences
let currentStateValue = store.getState()[ reducerKey ];
store.subscribe( () => {
const newStateValue = store.getState()[ reducerKey ];
if ( newStateValue !== currentStateValue ) {
currentStateValue = newStateValue;
window.localStorage.setItem( storageKey, JSON.stringify( currentStateValue ) );
}
} );
return store;
};
}