ImmutablePersistenceTransform.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // @flow
  2. import R from 'ramda'
  3. import Immutable from 'seamless-immutable'
  4. // is this object already Immutable?
  5. const isImmutable = R.has('asMutable')
  6. // change this Immutable object into a JS object
  7. const convertToJs = (state: Object) => state.asMutable({deep: true})
  8. // optionally convert this object into a JS object if it is Immutable
  9. const fromImmutable = R.when(isImmutable, convertToJs)
  10. // convert this JS object into an Immutable object
  11. const toImmutable = (raw: Object) => Immutable(raw)
  12. // the transform interface that redux-persist is expecting
  13. export default {
  14. out: (state: Object) => {
  15. console.log('retrieving', state)
  16. // --- HACKZORZ ---
  17. // Attach a empty-ass function to the object called `mergeDeep`.
  18. // This tricks redux-persist into just placing our Immutable object into the state tree
  19. // instead of trying to convert it to a POJO
  20. // https://github.com/rt2zz/redux-persist/blob/master/src/autoRehydrate.js#L55
  21. //
  22. // Another equal terrifying option would be to try to pass their other check
  23. // which is lodash isPlainObject.
  24. // --- END HACKZORZ ---
  25. state.mergeDeep = R.identity
  26. return toImmutable(state)
  27. },
  28. in: (raw: Object) => {
  29. // console.log({ storing: raw })
  30. return fromImmutable(raw)
  31. }
  32. }