Skip to content

Instantly share code, notes, and snippets.

@hacknlove
Created July 2, 2019 11:51
Show Gist options
  • Save hacknlove/9293ff770a7c8c6af16611656bb928aa to your computer and use it in GitHub Desktop.
Save hacknlove/9293ff770a7c8c6af16611656bb928aa to your computer and use it in GitHub Desktop.
Custom react hook useStorage for browser extension developers
import browser from 'webextension-polyfill'
import { useState, useEffect } from 'react'
function isDiferent (a, b) {
if (typeof a !== typeof b) {
return true
}
if (Array.isArray(a)) {
return arrayIsDifferent(a, b)
}
if (typeof a === 'object') {
return objectIsDiferent(a, b)
}
return a !== b
}
function arrayIsDifferent (a, b) {
if (a.length !== b.length) {
return true
}
return a.some((e, i) => {
return isDiferent(e, b[i])
})
}
function objectIsDiferent (a, b) {
const keysA = Object.keys(a)
const keysB = Object.keys(b)
if (arrayIsDifferent(keysA, keysB)) {
return true
}
return keysA.some((key) => {
return isDiferent(a[key], b[key])
})
}
export default function (key, first = null, area = 'sync') {
const [value, set] = useState(first)
browser.storage[area].get(key).then(sync => {
if (isDiferent(value, sync[key])) {
set(sync[key])
}
})
const storageOnChange = (object, _area) => {
if (area !== _area) {
return
}
if (!object[key]) {
return
}
if (isDiferent(value, object[key].newValue)) {
set(object[key].newValue)
}
}
useEffect(() => {
browser.storage.onChanged.addListener(storageOnChange)
return () => {
browser.storage.onChanged.removeListener(storageOnChange)
}
})
return value
}
@hacknlove
Copy link
Author

If enough people are using it, I will create a npm module, otherwise let's share it this way

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment