mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-03-30 06:02:00 +02:00
Flatten migrations, kvs lib, fix tabs
This commit is contained in:
39
src-web/hooks/useKeyValue.ts
Normal file
39
src-web/hooks/useKeyValue.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { buildKeyValueKey, getKeyValue, setKeyValue } from '../lib/keyValueStore';
|
||||
|
||||
const DEFAULT_NAMESPACE = 'app';
|
||||
|
||||
export function keyValueQueryKey({
|
||||
namespace = DEFAULT_NAMESPACE,
|
||||
key,
|
||||
}: {
|
||||
namespace?: string;
|
||||
key: string | string[];
|
||||
}) {
|
||||
return ['key_value', { namespace, key: buildKeyValueKey(key) }];
|
||||
}
|
||||
|
||||
export function useKeyValue<T extends string | number | boolean>({
|
||||
namespace = DEFAULT_NAMESPACE,
|
||||
key,
|
||||
initialValue,
|
||||
}: {
|
||||
namespace?: string;
|
||||
key: string | string[];
|
||||
initialValue: T;
|
||||
}) {
|
||||
const query = useQuery<T>({
|
||||
initialData: initialValue,
|
||||
queryKey: keyValueQueryKey({ namespace, key }),
|
||||
queryFn: async () => getKeyValue({ namespace, key, fallback: initialValue }),
|
||||
});
|
||||
|
||||
const mutate = useMutation<T, unknown, T>({
|
||||
mutationFn: (value) => setKeyValue<T>({ namespace, key, value }),
|
||||
});
|
||||
|
||||
return {
|
||||
value: query.data,
|
||||
set: (value: T) => mutate.mutate(value),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user