Created
June 22, 2022 08:14
-
-
Save eduardoacskimlinks/c4c251503871888f850d2a93216671c4 to your computer and use it in GitHub Desktop.
Wrapper for Chrome Local Storage API persistence for Chrome extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _get from "lodash/get" | |
import _isArray from "lodash/isArray" | |
// Placeholder to fetch your cache version | |
// CACHE_VERSION allows to reset user data after a version upgrade if it's required | |
import { CACHE_VERSION } from "config" | |
export const loadState = (keys) => { | |
const promise = new Promise((resolve, reject) => { | |
chrome.storage.local.get(CACHE_VERSION, (items) => { | |
const err = chrome.runtime.lastError | |
if (err) { | |
reject(err) | |
} else { | |
let inStorage = {} | |
if (_isArray(keys)) { | |
keys.forEach((key) => { | |
inStorage[key] = _get(items, [CACHE_VERSION, key]) | |
}) | |
} else { | |
inStorage = _get(items, [CACHE_VERSION], {}) | |
} | |
resolve(inStorage) | |
} | |
}) | |
}) | |
return promise | |
} | |
export const saveState = (state) => { | |
const promise = new Promise((resolve, reject) => { | |
chrome.storage.local.set({ [CACHE_VERSION]: state }, () => { | |
const err = chrome.runtime.lastError | |
if (err) { | |
reject(err) | |
} else { | |
resolve() | |
} | |
}) | |
}) | |
return promise | |
} | |
export const clearState = () => { | |
return chrome.storage.local.clear() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment