polemius/recoil-persist

Usage with localForage/IndexedDB/Dexie

NickVishwamitraJTY opened this issue · 2 comments

Thanks for creating this library. Saved me a ton of time and is super simple. I am however getting errors as I am using up all the provided space in local storage. Read up that using localforage or Dexie can get around this. Are we able to integrate these into recoil-persist?

Hi, you could pass the storage to recoilPersist function:

import { recoilPersist } from 'recoil-persist'

const { persistAtom } = recoilPersist({
  storage: localStorage, // configurate which stroage will be used to store the data
})

I can see that localForage has the same API as localStorage so it should just work.
But if storage has some different API then you could create a proxy for the storage:

const customStorage = () => {
  return {
    setItem: (key, value) => {
      // handle setItem
    },
    getItem: (key) => {
      // handle getItem
      // this function should return something
    },
    clear: () => {
      // clear the whole db
    },
  }
}

const { persistAtom } = recoilPersist({ storage: customStorage() })

Another example how you could encode values before putting it in localStorage

It moved! Thank you.

import localforage from "localforage";

localforage.config({
  driver: localforage.WEBSQL, // Force WebSQL; same as using setDriver()
  name: "myApp",
  version: 1.0,
  size: 4980736, // Size of database, in bytes. WebSQL-only for now.
  storeName: "keyvaluepairs", // Should be alphanumeric, with underscores.
  description: "some description",
});

const customStorage = () => {
  return {
    setItem: (key: any, value: any) => {
      // handle setItem
      localforage.setItem(key, value);
      // if err is non-null, we got an error
    },
    getItem: (key: any) => {
      // handle getItem
      // this function should return something
      const a = localforage.getItem(key, function (err, value) {
        // if err is non-null, we got an error. otherwise, value is the value
      });
      return a;
    },
    clear: () => {
      // clear the whole db
    },
  };
};

                                                                                                
const { persistAtom } = recoilPersist({
  key: "cssMsgStates", // this key is using to store data in local storage
  // @ts-ignoree
  storage: customStorage(),
});