import { useEffect, useState, useCallback } from "react"; import { get as getData, set as setData, del as delData } from "idb-keyval"; type usePersistenceReturn = [ value: S | undefined, setValue: (value: S | undefined) => void, loaded: boolean, deleteValue: () => void, ]; export function usePersistence( key: string, defaultValue: S | undefined = undefined, ): usePersistenceReturn { const [value, setInternalValue] = useState(defaultValue); const [loaded, setLoaded] = useState(false); const setValue = useCallback( (value: S | undefined) => { setInternalValue(value); async function update() { await setData(key, value); } update(); }, [key], ); const deleteValue = useCallback(async () => { await delData(key); setInternalValue(defaultValue); }, [key, defaultValue]); useEffect(() => { setLoaded(false); setInternalValue(defaultValue); async function load() { const value = await getData(key); if (typeof value !== "undefined") { setValue(value); } setLoaded(true); } load(); }, [key, defaultValue, setValue]); return [value, setValue, loaded, deleteValue]; }