polemius / recoil-persist

Package for recoil state manager to persist and rehydrate store
https://polemius.dev/recoil-persist/
MIT License
353 stars 39 forks source link

Make parseState or getState configurable #75

Closed tpict closed 1 year ago

tpict commented 1 year ago

Would it be possible to override one of these functions in the config option so we can store objects which aren't trivially deserialized from JSON? e.g. Set

polemius commented 1 year ago

You could pass Storage implementation to recoilPersist as storage, and change behavior of getItem and setItem. For example this storage encode everything in base64 and save it in localstorage. On read get the value from localstorage, decode and return it:

import { encode, decode } from 'js-base64';

const localStorageBase64 = () => {
  return {
    setItem: (key, value) => {
      localStorage.setItem(key, encode(value))
    },
    getItem: (key) => {
      const a =  localStorage.getItem(key)
      return decode(a || '')
    },
    clear: () => {
      localStorage.clear()
    },
  }
}

const { persistAtom } = recoilPersist({ key: 'abc1234', storage: localStorageBase64() })