Client: Created general useSavedState function

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

View File

@@ -20,7 +20,7 @@ import { ISpool } from "./model";
import { import {
TableState, TableState,
useInitialTableState, useInitialTableState,
useShowArchive, useSavedState,
useStoreInitialState, useStoreInitialState,
} from "../../utils/saveload"; } from "../../utils/saveload";
import { import {
@@ -55,7 +55,10 @@ export const SpoolList: React.FC<IResourceComponentsProps> = () => {
const initialState = useInitialTableState("spoolList"); const initialState = useInitialTableState("spoolList");
// State for the switch to show archived spools // 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 // Fetch data from the API
const { const {

View File

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