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

45 lines
1.1 KiB
JavaScript
Raw Normal View History

import { useState } from 'react';
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;
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);
function setValueAndLocalStorage(newValue) {
if (key && localStorageAvailable && value !== newValue) {
localStorage.setItem(key, typeof newValue === 'object' ? JSON.stringify(newValue) : newValue);
2019-06-11 20:10:58 +02:00
}
setValue(newValue);
}
return [value, setValueAndLocalStorage];
2019-06-11 20:10:58 +02:00
}