mirror of
https://github.com/streetwriters/notesnook.git
synced 2026-09-03 04:31:46 +02:00
21 lines
430 B
JavaScript
21 lines
430 B
JavaScript
import { useState } from "react";
|
|
|
|
export const usePersistentState = (key, def) => {
|
|
let value = window.localStorage.getItem(key) || def;
|
|
const defState = tryParse(value);
|
|
const [k, setKey] = useState(defState);
|
|
const _setKey = s => {
|
|
setKey(s);
|
|
window.localStorage.setItem(key, s);
|
|
};
|
|
return [k, _setKey];
|
|
};
|
|
|
|
function tryParse(val) {
|
|
try {
|
|
return JSON.parse(val);
|
|
} catch (e) {
|
|
return val;
|
|
}
|
|
}
|