polemius / recoil-persist

Package for recoil state manager to persist and rehydrate store

Home Page:https://polemius.dev/recoil-persist/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Persist state using chrome storage api instead of local storage?

smartify-jia opened this issue · comments

Hi there,
Thanks for developing this wonderful package. It saves me lots of time on setting up state management for my chrome extension.
Just wondering if it's possible to persist using chrome storage instead of localStorage? As I'm developing a chrome extension, it would be great if I could use chrome storage API to store my state so that I can access my data from different area (i.e. contentScript, backgroundScript/serviceWorker, popUp).

I really appreciate any help you can provide. Thanks in advance

Something like this

const localStorageBase64 = () => {
  return {
    setItem: (key, value) => {
      chrome.storage.local.set(key, encode(value))
    },
    getItem: (key) => {
      const a = chrome.storage.local.get(key)
      return decode(a || '')
    },
    clear: () => {
      chrome.storage.local.clear()
    }
  }
}

const { persistAtom } = recoilPersist({
  key: 'recoil-storage', // this key is using to store data in local storage
  storage: localStorageBase64() // configurate which stroage will be used to store the data
})

Hi,
Thank you for the issue.
The code that you provided works?

Hi,
Thank you so much for the speedy reply.
No, it does not work. I think it only worked with localStorage, but it would be great if recoil-persist could utilise chrome storage API.
It would be very beneficial for React chrome extension developers IMO. Definitely let me know if there's anything that I can help or do in that area. Thanks.

@smartify-jia please try this code:

const localStorageBase64 = () => {
  return {
    setItem: (key, value) => {
      return new Promise((resolve, reject) => {
        try {
          chrome.storage.local.set({key: value}, function() {
            resolve();
          });
        } catch (ex) {
          reject(ex);
        }
      });
    },
    getItem: (key) => {
      return new Promise((resolve, reject) => {
        try {
          chrome.storage.local.get(key, function(value) {
            resolve(value[key]);
          });
        } catch (ex) {
          reject(ex);
        }
      });
    },
    clear: () => {
      chrome.storage.local.clear()
    }
  }
}

Hi,

Thank you so much for the solution. It works!

I am happy to be your beta tester or feel free to drop me an email if you need any help in the future.

Cheers