Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/resources/scripts/plugins/usePersistedState.ts
7458 views
1
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
2
3
export function usePersistedState<S = undefined>(
4
key: string,
5
defaultValue: S
6
): [S | undefined, Dispatch<SetStateAction<S | undefined>>] {
7
const [state, setState] = useState(() => {
8
try {
9
const item = localStorage.getItem(key);
10
11
return JSON.parse(item || String(defaultValue));
12
} catch (e) {
13
console.warn('Failed to retrieve persisted value from store.', e);
14
15
return defaultValue;
16
}
17
});
18
19
useEffect(() => {
20
localStorage.setItem(key, JSON.stringify(state));
21
}, [key, state]);
22
23
return [state, setState];
24
}
25
26