Yuki Takei 3 лет назад
Родитель
Сommit
415be59ba6
2 измененных файлов с 15 добавлено и 22 удалено
  1. 5 12
      packages/app/src/stores/use-context-swr.tsx
  2. 10 10
      packages/app/src/stores/use-static-swr.tsx

+ 5 - 12
packages/app/src/stores/use-context-swr.tsx

@@ -1,9 +1,10 @@
 import assert from 'assert';
 
 import {
-  Key, SWRConfiguration, SWRResponse, useSWRConfig,
+  Key, SWRConfiguration, SWRResponse,
 } from 'swr';
-import useSWRImmutable from 'swr/immutable';
+
+import { useStaticSWR } from './use-static-swr';
 
 
 export function useContextSWR<Data, Error>(key: Key): SWRResponse<Data, Error>;
@@ -20,17 +21,9 @@ export function useContextSWR<Data, Error>(
 
   assert.notStrictEqual(configuration?.fetcher, null, 'useContextSWR does not support \'configuration.fetcher\'');
 
-  const { cache } = useSWRConfig();
-  const swrResponse = useSWRImmutable(key, null, {
-    ...configuration,
-    fallbackData: configuration?.fallbackData ?? cache.get(key)?.data,
-  });
-
-  // write data to cache directly
-  if (data !== undefined) {
-    cache.set(key, { ...cache.get(key), data });
-  }
+  const swrResponse = useStaticSWR(key, data, configuration);
 
+  // overwrite mutate
   const result = Object.assign(swrResponse, { mutate: () => { throw Error('mutate can not be used in context') } });
 
   return result;

+ 10 - 10
packages/app/src/stores/use-static-swr.tsx

@@ -1,9 +1,7 @@
-import { useEffect } from 'react';
-
 import assert from 'assert';
 
 import {
-  mutate, Key, SWRConfiguration, SWRResponse,
+  Key, SWRConfiguration, SWRResponse, useSWRConfig,
 } from 'swr';
 import useSWRImmutable from 'swr/immutable';
 
@@ -22,14 +20,16 @@ export function useStaticSWR<Data, Error>(
 
   assert.notStrictEqual(configuration?.fetcher, null, 'useStaticSWR does not support \'configuration.fetcher\'');
 
-  const swrResponse = useSWRImmutable(key, null, configuration);
+  const { cache } = useSWRConfig();
+  const swrResponse = useSWRImmutable(key, null, {
+    ...configuration,
+    fallbackData: configuration?.fallbackData ?? cache.get(key)?.data,
+  });
 
-  // Do mutate with `data` from args
-  useEffect(() => {
-    if (data !== undefined) {
-      mutate(key, data);
-    }
-  }, [data, key]);
+  // write data to cache directly
+  if (data !== undefined) {
+    cache.set(key, { ...cache.get(key), data });
+  }
 
   return swrResponse;
 }