Client: Created general useSavedState function

This commit is contained in:
Donkie
2023-07-15 14:38:40 +02:00
parent 7c23156d85
commit df89a0c8a5
2 changed files with 12 additions and 9 deletions

View File

@@ -60,17 +60,17 @@ export function useStoreInitialState(tableId: string, state: TableState) {
}, [tableId, state.showColumns]);
}
export function useShowArchive(tableId: string) {
const [showArchive, setShowArchive] = React.useState(() => {
const savedShowArchive = isLocalStorageAvailable ? localStorage.getItem(`${tableId}-showArchive`) : null;
return savedShowArchive ? JSON.parse(savedShowArchive) : false;
export function useSavedState<T>(id: string, defaultValue: T) {
const [state, setState] = React.useState<T>(() => {
const savedState = isLocalStorageAvailable ? localStorage.getItem(`savedStates-${id}`) : null;
return savedState ? JSON.parse(savedState) : defaultValue;
});
React.useEffect(() => {
if (isLocalStorageAvailable) {
localStorage.setItem(`${tableId}-showArchive`, JSON.stringify(showArchive));
localStorage.setItem(`savedStates-${id}`, JSON.stringify(state));
}
}, [tableId, showArchive]);
}, [id, state]);
return [showArchive, setShowArchive] as const;
return [state, setState] as const;
}