mirror of
https://github.com/blakeblackshear/frigate.git
synced 2024-12-23 19:11:14 +01:00
ff2948a76b
* draggable/resizable cameras in camera groups on desktop/tablets * fix edit button location on tablets * assume 1rem is 16px
52 lines
1.2 KiB
TypeScript
52 lines
1.2 KiB
TypeScript
import { useEffect, useState, useCallback } from "react";
|
|
import { get as getData, set as setData, del as delData } from "idb-keyval";
|
|
|
|
type usePersistenceReturn<S> = [
|
|
value: S | undefined,
|
|
setValue: (value: S | undefined) => void,
|
|
loaded: boolean,
|
|
deleteValue: () => void,
|
|
];
|
|
|
|
export function usePersistence<S>(
|
|
key: string,
|
|
defaultValue: S | undefined = undefined,
|
|
): usePersistenceReturn<S> {
|
|
const [value, setInternalValue] = useState<S | undefined>(defaultValue);
|
|
const [loaded, setLoaded] = useState<boolean>(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];
|
|
}
|