From 1fb7a6b1a2a5bf99497d055755d8a467093adbdf Mon Sep 17 00:00:00 2001 From: Vedant Chainani Date: Sat, 14 Sep 2024 02:10:46 +0530 Subject: [PATCH] chore: add new hook for storing multiple values --- packages/client-react-hooks/src/index.ts | 1 + .../src/use-nil-store-values.ts | 49 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 packages/client-react-hooks/src/use-nil-store-values.ts diff --git a/packages/client-react-hooks/src/index.ts b/packages/client-react-hooks/src/index.ts index 3c697d1..38680d2 100644 --- a/packages/client-react-hooks/src/index.ts +++ b/packages/client-react-hooks/src/index.ts @@ -7,6 +7,7 @@ export * from "./use-nil-fetch-value"; export * from "./use-nil-set-store-acl"; export * from "./use-nil-store-program"; export * from "./use-nil-store-value"; +export * from "./use-nil-store-values"; export * from "./use-nil-update-value"; export * from "./use-nillion"; export * from "./use-nillion-auth"; diff --git a/packages/client-react-hooks/src/use-nil-store-values.ts b/packages/client-react-hooks/src/use-nil-store-values.ts new file mode 100644 index 0000000..a033557 --- /dev/null +++ b/packages/client-react-hooks/src/use-nil-store-values.ts @@ -0,0 +1,49 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; + +import { Days, NadaValues, StoreAcl, StoreId } from "@nillion/client-core"; + +import { createStoreCacheKey } from "./cache-key"; +import { nilHookBaseResult, UseNilHook } from "./nil-hook-base"; +import { useNillion } from "./use-nillion"; + +interface ExecuteArgs { + values: NadaValues; + ttl: Days; + acl?: StoreAcl; +} + +type ExecuteResult = StoreId; + +type UseNilStoreValues = UseNilHook; + +export const useNilStoreValues = (): UseNilStoreValues => { + const { client: nilClient } = useNillion(); + const queryClient = useQueryClient(); + + const mutationFn = async (args: ExecuteArgs): Promise => { + const { values, ttl, acl } = args; + const response = await nilClient.storeValues({ + values, + ttl, + acl, + }); + if (response.err) throw response.err as Error; + + const id = response.ok; + const key = createStoreCacheKey(id); + queryClient.setQueryData(key, id); + return id; + }; + + const mutate = useMutation({ + mutationFn, + }); + + return { + execute: (args: ExecuteArgs) => { + mutate.mutate(args); + }, + executeAsync: async (args: ExecuteArgs) => mutate.mutateAsync(args), + ...nilHookBaseResult(mutate), + }; +};