3034f4ce6c
* bring in ody styles; modify; cleanup * workflow * workflow * v0.52.6-alpha.teststyles.1 * fix hook * v0.52.6-alpha.teststyles.2 * style fixes * fix pagination styling * v0.52.6-alpha.teststyles.3 * wallet icon was bad * restore deploy script * fixes * fix player close button * modal inputs * cleanup * cleanup * fix staked indicator * fix profile menu button skel delay * fix view-all-playlists hover * fix overlay buttons on collection page * fix header buttons
67 lines
1.6 KiB
JavaScript
67 lines
1.6 KiB
JavaScript
import { useState, useEffect } from 'react';
|
|
|
|
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));
|
|
}
|
|
|
|
export default function usePersistedState(key, firstTimeDefault) {
|
|
// If no key is passed in, act as a normal `useState`
|
|
let defaultValue;
|
|
let localStorageAvailable;
|
|
|
|
try {
|
|
localStorageAvailable = Boolean(window.localStorage);
|
|
} catch (e) {
|
|
localStorageAvailable = false;
|
|
}
|
|
if (key && localStorageAvailable) {
|
|
let item = localStorage.getItem(key);
|
|
|
|
if (item) {
|
|
let parsedItem;
|
|
try {
|
|
parsedItem = JSON.parse(item);
|
|
} catch (e) {}
|
|
|
|
if (parsedItem !== undefined) {
|
|
defaultValue = parsedItem;
|
|
} else {
|
|
defaultValue = item;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!defaultValue && defaultValue !== false) {
|
|
defaultValue = firstTimeDefault;
|
|
}
|
|
|
|
const [value, setValue] = useState(defaultValue);
|
|
|
|
if (key && !Array.isArray(listeners[key])) {
|
|
listeners[key] = [];
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (key && localStorageAvailable) {
|
|
localStorage.setItem(key, typeof value === 'object' ? JSON.stringify(value) : value);
|
|
}
|
|
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]);
|
|
|
|
return [value, getSetAllValues(key, setValue)];
|
|
}
|