import { useCallback, useEffect, useRef, useState } from "react"; import type { Storage } from "../identity/types"; import { WebStorage } from "../identity/storage"; type Primitives = string | number | boolean | null; type Arr = AllowedValue[]; type Obj = { [key in string]: AllowedValue } & { [key in string]?: AllowedValue | undefined; }; type AllowedValue = Primitives | Arr | Obj; type SharedOptions = { key: string; /** * Called each time the value in storage changes or is loaded. * * You can modify the value before it is set in the state. */ preprocessValue?: (value: Exclude) => TValue; /** * @defaultValue WebStorage */ storage?: Storage; }; type UseStorageWithoutInitialValue = { initialValue?: never; } & SharedOptions; type UseStorageOptionsWithInitialValue = { initialValue: TValue; } & SharedOptions; type UseStorageOptions = { initialValue?: TValue; } & SharedOptions; type Setter = ( value: TValue | ((prevState: TValue) => TValue) ) => Promise; const defaultStorage = new WebStorage(); export function useStorage( options: UseStorageWithoutInitialValue ): [TValue | undefined, Setter]; export function useStorage( options: UseStorageOptionsWithInitialValue ): [TValue, Setter]; export function useStorage< TValue extends AllowedValue | undefined = undefined, >({ key, initialValue, preprocessValue, storage = defaultStorage, }: UseStorageOptions): [ TValue | undefined, Setter, ] { const storageRef = useRef(storage); const preprocessValueRef = useRef(preprocessValue); preprocessValueRef.current = preprocessValue; const initialValueRef = useRef(initialValue); const [value, setValue] = useState( initialValueRef.current ); useEffect(() => { function isValueNotUndefined( newValue: TNewValue ): newValue is Exclude { return newValue !== undefined; } const listener = (newValue: TValue | undefined): void => { if (!isValueNotUndefined(newValue)) { /** * If new value is undefined, use initial value. * * This can happen when you load the app for first time and there is no value * in the storage or when you remove the value from the storage. */ setValue(initialValueRef.current); return; } setValue( preprocessValueRef.current ? preprocessValueRef.current(newValue) : newValue ); }; const unsubscribe = storageRef.current.watch(key, listener); return () => { unsubscribe(); }; }, [key]); const setState: Setter = useCallback( async (setter) => { await storageRef.current.set(key, (currentState) => { if (typeof setter !== "function") { return setter; } return setter( currentState === undefined ? initialValueRef.current : currentState ); }); }, [key] ); return [value, setState]; }