1
- import { useEffect } from 'react'
1
+ import { useEffect , useRef } from 'react'
2
2
import { Middleware , SWRHook , State , useSWRConfig } from 'swr'
3
3
4
4
type SwrCache = [ string , State ] [ ]
@@ -11,6 +11,9 @@ const cachedKeys = new Set<string>()
11
11
const validatedKeys = new Set < string > ( )
12
12
13
13
/**
14
+ * This hook should be used before the corresponding useSWR() call,
15
+ * otherwise SWR will consider the fetched data stale and send a new request.
16
+ *
14
17
* @param key - **the key is not supposed to be dynamic.**
15
18
* @param validate - validates the cached state, if it returns false, the state will be discarded.
16
19
* This function will only run once for each key (because we want it to validate cached data, not fresh data).
@@ -23,7 +26,14 @@ export function useSWRCache(
23
26
24
27
const { cache, mutate } = useSWRConfig ( )
25
28
26
- useEffect ( ( ) => {
29
+ const validated = useRef ( false )
30
+
31
+ // Only run once. We cannot use useEffect() here because useSWR() fires request synchronously,
32
+ // if we mutate() the state in useEffect(), SWR will think the fetched data is stale,
33
+ // discard it, and attempt to fire a new request, which will be blocked if dedupingInterval is set.
34
+ if ( ! validated . current ) {
35
+ validated . current = true
36
+
27
37
if ( ! validatedKeys . has ( key ) ) {
28
38
validatedKeys . add ( key )
29
39
@@ -48,7 +58,7 @@ export function useSWRCache(
48
58
}
49
59
}
50
60
}
51
- } , [ ] )
61
+ }
52
62
}
53
63
54
64
/**
0 commit comments