Yuken Tezuka 3 лет назад
Родитель
Сommit
513342703c
1 измененных файлов с 30 добавлено и 0 удалено
  1. 30 0
      packages/app/src/stores/use-context-swr.tsx

+ 30 - 0
packages/app/src/stores/use-context-swr.tsx

@@ -0,0 +1,30 @@
+import {
+  Key, SWRConfiguration, SWRResponse,
+} from 'swr';
+
+import { useStaticSWR } from './use-static-swr';
+
+// omit mutate from swr response because context shouldn't be changed
+type ContextSWRResponse<Data = any, Error = any> = Omit<SWRResponse<Data, Error>, 'mutate'>
+
+export function useContextSWR<Data, Error>(key: Key): ContextSWRResponse<Data, Error>;
+export function useContextSWR<Data, Error>(key: Key, data: Data | undefined): ContextSWRResponse<Data, Error>;
+export function useContextSWR<Data, Error>(key: Key, data: Data | undefined,
+  configuration: SWRConfiguration<Data, Error> | undefined): ContextSWRResponse<Data, Error>;
+
+export function useContextSWR<Data, Error>(
+    ...args: readonly [Key]
+    | readonly [Key, Data | undefined]
+    | readonly [Key, Data | undefined, SWRConfiguration<Data, Error> | undefined]
+): ContextSWRResponse<Data, Error> {
+  const [key, data, configuration] = args;
+
+  const swrResponse = useStaticSWR<Data, Error>(key, data, configuration);
+  const { data: responseData, error, isValidating } = swrResponse;
+
+  return {
+    data: responseData,
+    error,
+    isValidating,
+  };
+}