2020-04-26 00:52:32 +00:00
|
|
|
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
|
|
|
|
|
2021-10-03 22:36:58 +00:00
|
|
|
export function usePersistedState<S extends any = undefined> (key: string, defaultValue: S): [ S, Dispatch<SetStateAction<S>> ] {
|
2020-07-05 01:30:50 +00:00
|
|
|
const [ state, setState ] = useState(
|
2020-04-26 00:52:32 +00:00
|
|
|
() => {
|
|
|
|
try {
|
|
|
|
const item = localStorage.getItem(key);
|
|
|
|
|
2021-08-02 18:23:38 +00:00
|
|
|
if (item === null) {
|
|
|
|
return defaultValue;
|
|
|
|
}
|
|
|
|
|
|
|
|
return JSON.parse(item || String(defaultValue));
|
2020-04-26 00:52:32 +00:00
|
|
|
} catch (e) {
|
|
|
|
console.warn('Failed to retrieve persisted value from store.', e);
|
|
|
|
|
|
|
|
return defaultValue;
|
|
|
|
}
|
2021-01-21 04:07:52 +00:00
|
|
|
},
|
2020-04-26 00:52:32 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
useEffect(() => {
|
2020-07-05 01:30:50 +00:00
|
|
|
localStorage.setItem(key, JSON.stringify(state));
|
|
|
|
}, [ key, state ]);
|
2020-04-26 00:52:32 +00:00
|
|
|
|
|
|
|
return [ state, setState ];
|
|
|
|
}
|