|
1 | | -import { saveSessionState } from './persistenceHelpers' |
2 | | -import { throttle } from 'lodash' |
3 | | -import { isTestMode } from './utils' |
| 1 | +import { loadSessionState, saveSessionState } from './persistenceHelpers' |
4 | 2 |
|
5 | | -const DEFAULT_DEBOUNCE_INTERVAL = 500 |
| 3 | +let CACHED_SESSION_STATE = loadSessionState() |
6 | 4 |
|
7 | 5 | // Adds store subscription that persists session state in local storage |
8 | | -function enhancer ({ |
9 | | - persist=true, |
10 | | - debounce=true, |
11 | | - debounceInTestMode=false, |
12 | | - debounceInterval=DEFAULT_DEBOUNCE_INTERVAL, |
13 | | -}={}) { |
| 6 | +function enhancer ({ persist=true }={}) { |
14 | 7 | return function enhance (createStore) { |
15 | 8 | return function newCreateStore (...args) { |
16 | 9 | const store = createStore(...args) |
17 | 10 | if (!persist) return store |
18 | | - // Define subscription function |
19 | | - function persistState () { |
20 | | - const state = store.getState() |
21 | | - if (!state.sessions) throw new Error('redux-sessions: error when attempting to save state. Did you remember to attach the reducer at key `sessions`?') |
22 | | - return saveSessionState(state.sessions) |
23 | | - } |
24 | | - // Don't debounce in test mode, unless otherwise specified |
25 | | - const doDebounce = isTestMode() |
26 | | - ? debounceInTestMode |
27 | | - : debounce |
28 | | - const subscription = doDebounce ? throttle(persistState, debounceInterval) : persistState |
29 | | - store.subscribe(subscription) |
| 11 | + store.subscribe(() => { |
| 12 | + const sessionState = store.getState().sessions |
| 13 | + if (!sessionState) throw new Error('redux-sessions: error when attempting to save state. Did you remember to attach the reducer at key `sessions`?') |
| 14 | + if (sessionState === CACHED_SESSION_STATE) return |
| 15 | + CACHED_SESSION_STATE = sessionState |
| 16 | + return saveSessionState(sessionState) |
| 17 | + }) |
30 | 18 | return store |
31 | 19 | } |
32 | 20 | } |
|
0 commit comments