-
Notifications
You must be signed in to change notification settings - Fork 867
/
getStoredState.js
50 lines (46 loc) · 1.37 KB
/
getStoredState.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
// @flow
import type { PersistConfig } from './types'
import { KEY_PREFIX } from './constants'
export default function getStoredState(
config: PersistConfig
): Promise<Object | void> {
const transforms = config.transforms || []
const storageKey = `${
config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX
}${config.key}`
const storage = config.storage
const debug = config.debug
let deserialize
if (config.deserialize === false) {
deserialize = x => x
} else if (typeof config.deserialize === 'function') {
deserialize = config.deserialize
} else {
deserialize = defaultDeserialize
}
return storage.getItem(storageKey).then(serialized => {
if (!serialized) return undefined
else {
try {
let state = {}
let rawState = deserialize(serialized)
Object.keys(rawState).forEach(key => {
state[key] = transforms.reduceRight((subState, transformer) => {
return transformer.out(subState, key, rawState)
}, deserialize(rawState[key]))
})
return state
} catch (err) {
if (process.env.NODE_ENV !== 'production' && debug)
console.log(
`redux-persist/getStoredState: Error restoring data ${serialized}`,
err
)
throw err
}
}
})
}
function defaultDeserialize(serial) {
return JSON.parse(serial)
}