From 3cab6166a327fdce24a55526435c6d4c8409c091 Mon Sep 17 00:00:00 2001 From: Donkie Date: Sat, 15 Jul 2023 14:38:40 +0200 Subject: [PATCH] Client: Created general useSavedState function --- client/src/pages/spools/list.tsx | 7 +++++-- client/src/utils/saveload.ts | 14 +++++++------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/client/src/pages/spools/list.tsx b/client/src/pages/spools/list.tsx index 36c9c46..0918c30 100644 --- a/client/src/pages/spools/list.tsx +++ b/client/src/pages/spools/list.tsx @@ -20,7 +20,7 @@ import { ISpool } from "./model"; import { TableState, useInitialTableState, - useShowArchive, + useSavedState, useStoreInitialState, } from "../../utils/saveload"; import { @@ -55,7 +55,10 @@ export const SpoolList: React.FC = () => { const initialState = useInitialTableState("spoolList"); // State for the switch to show archived spools - const [showArchived, setShowArchived] = useShowArchive("spoolList"); + const [showArchived, setShowArchived] = useSavedState( + "spoolList-showArchived", + false + ); // Fetch data from the API const { diff --git a/client/src/utils/saveload.ts b/client/src/utils/saveload.ts index a20aaa0..6677e7e 100644 --- a/client/src/utils/saveload.ts +++ b/client/src/utils/saveload.ts @@ -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(id: string, defaultValue: T) { + const [state, setState] = React.useState(() => { + 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; }