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

Feature Request: transformer like in redux-persist #40

Closed jembach closed 3 years ago

jembach commented 3 years ago

Hi,

currently I'm experimenting to completely replace redux with recoil and react state. One of the core features I'm using and that is not available currently are transformers.

As an example I would like to encrypt the data in the storage and this could be done by a transformer.

Before suggesting a pull request with the feature I would like to ask @polemius and the community if they have some suggestions for that or conditions to this feature.

When we find a consent I'm start developing this feature for generic transformers.

polemius commented 3 years 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() })
jembach commented 3 years ago

Good call. I would suggest to share a small example in the readme to increase adoption rate for this package.