Created
February 2, 2020 05:11
-
-
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
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
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