getStoredState.js.flow 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // @flow
  2. import type { PersistConfig } from './types'
  3. import { KEY_PREFIX } from './constants'
  4. export default function getStoredState(
  5. config: PersistConfig
  6. ): Promise<Object | void> {
  7. const transforms = config.transforms || []
  8. const storageKey = `${
  9. config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX
  10. }${config.key}`
  11. const storage = config.storage
  12. const debug = config.debug
  13. let deserialize
  14. if (config.deserialize === false) {
  15. deserialize = x => x
  16. } else if (typeof config.deserialize === 'function') {
  17. deserialize = config.deserialize
  18. } else {
  19. deserialize = defaultDeserialize
  20. }
  21. return storage.getItem(storageKey).then(serialized => {
  22. if (!serialized) return undefined
  23. else {
  24. try {
  25. let state = {}
  26. let rawState = deserialize(serialized)
  27. Object.keys(rawState).forEach(key => {
  28. state[key] = transforms.reduceRight((subState, transformer) => {
  29. return transformer.out(subState, key, rawState)
  30. }, deserialize(rawState[key]))
  31. })
  32. return state
  33. } catch (err) {
  34. if (process.env.NODE_ENV !== 'production' && debug)
  35. console.log(
  36. `redux-persist/getStoredState: Error restoring data ${serialized}`,
  37. err
  38. )
  39. throw err
  40. }
  41. }
  42. })
  43. }
  44. function defaultDeserialize(serial) {
  45. return JSON.parse(serial)
  46. }