2023-12-08 14:33:22 +01:00
|
|
|
import { useEffect, useState, useCallback } from "react";
|
2024-05-07 16:28:10 +02:00
|
|
|
import { get as getData, set as setData, del as delData } from "idb-keyval";
|
2023-12-08 14:33:22 +01:00
|
|
|
|
2024-02-28 15:16:16 +01:00
|
|
|
type usePersistenceReturn<S> = [
|
|
|
|
value: S | undefined,
|
2024-03-14 15:27:27 +01:00
|
|
|
setValue: (value: S | undefined) => void,
|
2023-12-16 00:24:50 +01:00
|
|
|
loaded: boolean,
|
2024-05-07 16:28:10 +02:00
|
|
|
deleteValue: () => void,
|
2023-12-16 00:24:50 +01:00
|
|
|
];
|
|
|
|
|
2024-02-28 15:16:16 +01:00
|
|
|
export function usePersistence<S>(
|
2023-12-08 14:33:22 +01:00
|
|
|
key: string,
|
2024-02-28 23:23:56 +01:00
|
|
|
defaultValue: S | undefined = undefined,
|
2024-02-28 15:16:16 +01:00
|
|
|
): usePersistenceReturn<S> {
|
|
|
|
const [value, setInternalValue] = useState<S | undefined>(defaultValue);
|
2023-12-16 00:24:50 +01:00
|
|
|
const [loaded, setLoaded] = useState<boolean>(false);
|
2023-12-08 14:33:22 +01:00
|
|
|
|
|
|
|
const setValue = useCallback(
|
2024-03-14 15:27:27 +01:00
|
|
|
(value: S | undefined) => {
|
2023-12-08 14:33:22 +01:00
|
|
|
setInternalValue(value);
|
|
|
|
async function update() {
|
|
|
|
await setData(key, value);
|
|
|
|
}
|
|
|
|
|
|
|
|
update();
|
|
|
|
},
|
2024-02-28 23:23:56 +01:00
|
|
|
[key],
|
2023-12-08 14:33:22 +01:00
|
|
|
);
|
|
|
|
|
2024-05-07 16:28:10 +02:00
|
|
|
const deleteValue = useCallback(async () => {
|
|
|
|
await delData(key);
|
|
|
|
setInternalValue(defaultValue);
|
|
|
|
}, [key, defaultValue]);
|
|
|
|
|
2023-12-08 14:33:22 +01:00
|
|
|
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]);
|
|
|
|
|
2024-05-07 16:28:10 +02:00
|
|
|
return [value, setValue, loaded, deleteValue];
|
2023-12-08 14:33:22 +01:00
|
|
|
}
|