elgerlambert / redux-localstorage

Store enhancer that syncs (a subset) of your Redux store state to localstorage.
MIT License
1.32k stars 107 forks source link

Suggestions how to handle moment.js objects? #36

Closed RanzQ closed 8 years ago

RanzQ commented 8 years ago

I have some moment objects in my combined state. They might be at the root of the sub-state or one step deeper. I was thinking of setting up serialize to check root keys and the keys of possible objects if they contain moment objects and then stringify them as 'moment:' + aMoment.valueOf(). Then in deserialize would check for strings with 'moment:' and convert them back. I already use .valueOf() for json transfers cause it performs a lot better than the string representation.

Any other ways to handle this?

RanzQ commented 8 years ago

Actually it was easy to just customize the JSON.stringify process. For some reason Moment instances get converted to strings before reaching the replacer function (at least in Chrome) so I used a regex to check for dates:

let persistStateConfig = {
  serialize: (collection) => {
    return JSON.stringify(collection, function (k, v) {
      if (typeof v === 'string' && v.match(RE_ISO_DATE)) {
        return 'moment:' + moment(v).valueOf()
      }
      return v
    })
  },
  deserialize: (serializedData) => {
    return JSON.parse(serializedData, function (k, v) {
      if (typeof v === 'string' && v.includes('moment:')) {
        return moment(parseInt(v.split(':')[1], 10))
      }
      return v
    })
  }
}
VivienAdnot commented 7 years ago

Hello @RanzQ can you provide RE_ISO_DATE please ? Thank you

RanzQ commented 7 years ago

@VivienAdnot Here: const RE_ISO_DATE = /\d{4}-[01]\d-[0-3]\dT?[0-2]\d:[0-5]\d(?::[0-5]\d(?:.\d{1,6})?)?(?:([+-])([0-2]\d):?([0-5]\d)|Z)/