lbry-desktop/ui/effects/use-persisted-state.js

68 lines
1.6 KiB
JavaScript
Raw Normal View History

import { useState, useEffect } from 'react';
2019-06-11 20:10:58 +02:00
2020-05-01 07:07:20 +02:00
const listeners = {};
function getSetAllValues(key, setValue) {
if (!key) {
// If no key just return the normal setValue function
return setValue;
}
return value => listeners[key].forEach(fn => fn(value));
}
2019-06-11 20:10:58 +02:00
export default function usePersistedState(key, firstTimeDefault) {
// If no key is passed in, act as a normal `useState`
let defaultValue;
let localStorageAvailable;
2020-05-01 07:07:20 +02:00
try {
localStorageAvailable = Boolean(window.localStorage);
} catch (e) {
localStorageAvailable = false;
}
if (key && localStorageAvailable) {
2019-08-13 07:35:13 +02:00
let item = localStorage.getItem(key);
if (item) {
let parsedItem;
try {
parsedItem = JSON.parse(item);
} catch (e) {}
if (parsedItem !== undefined) {
2019-08-13 07:35:13 +02:00
defaultValue = parsedItem;
} else {
defaultValue = item;
}
2019-06-27 01:59:27 +02:00
}
2019-06-11 20:10:58 +02:00
}
if (!defaultValue && defaultValue !== false) {
2019-06-11 20:10:58 +02:00
defaultValue = firstTimeDefault;
}
const [value, setValue] = useState(defaultValue);
2020-05-01 07:07:20 +02:00
if (key && !Array.isArray(listeners[key])) {
listeners[key] = [];
}
useEffect(() => {
if (key && localStorageAvailable) {
localStorage.setItem(key, typeof value === 'object' ? JSON.stringify(value) : value);
2019-06-11 20:10:58 +02:00
}
2020-05-01 07:07:20 +02:00
if (key) {
// add hook on mount
listeners[key].push(setValue);
}
return () => {
if (key) {
// remove hook on unmount
listeners[key] = listeners[key].filter(listener => listener !== setValue);
}
};
}, [key, value, localStorageAvailable]);
2019-06-11 20:10:58 +02:00
2020-05-01 07:07:20 +02:00
return [value, getSetAllValues(key, setValue)];
2019-06-11 20:10:58 +02:00
}