Skip to content

Instantly share code, notes, and snippets.

@t3dotgg
Created February 2, 2020 05:11
Show Gist options
  • Save t3dotgg/98543225df6669160e4f20f3fc4b7812 to your computer and use it in GitHub Desktop.
Save t3dotgg/98543225df6669160e4f20f3fc4b7812 to your computer and use it in GitHub Desktop.
Custom hook to use Chrome's sync storage api as a stateful variable store. Drop-in replacement for useState
const useChromeStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
chrome.storage.sync.get([key], result => {
if (result && result[key] !== undefined) {
setStoredValue(result[key]);
} else {
chrome.storage.sync.set({ [key]: initialValue }, () => {});
}
});
return initialValue;
});
const setValue = value => {
const newVal = value instanceof Function ? value(storedValue) : value;
setStoredValue(newVal);
chrome.storage.sync.set({ [key]: newVal }, () => {});
};
return [storedValue, setValue];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment