lbry-desktop/src/ui/util/use-persisted-state.js

31 lines
664 B
JavaScript
Raw Normal View History

2019-06-11 20:10:58 +02:00
import { useState, useEffect } from 'react';
export default function usePersistedState(key, firstTimeDefault) {
// If no key is passed in, act as a normal `useState`
let defaultValue;
if (key) {
2019-06-27 01:59:27 +02:00
const item = localStorage.getItem(key);
if (item === 'true') {
defaultValue = true;
} else if (item === 'false') {
defaultValue = false;
2019-07-01 05:30:42 +02:00
} else {
defaultValue = item;
2019-06-27 01:59:27 +02:00
}
2019-06-11 20:10:58 +02:00
}
if (!defaultValue) {
defaultValue = firstTimeDefault;
}
const [value, setValue] = useState(defaultValue);
useEffect(() => {
if (key) {
localStorage.setItem(key, value);
}
}, [key, value]);
return [value, setValue];
}