Skip to content

Commit 1339ff7

Browse files
authored
Merge pull request #139 from MaaAssistantArknights/dev
fix: broken levels cache
2 parents a23ac06 + 25803d8 commit 1339ff7

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/utils/swr-cache.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect } from 'react'
1+
import { useEffect, useRef } from 'react'
22
import { Middleware, SWRHook, State, useSWRConfig } from 'swr'
33

44
type SwrCache = [string, State][]
@@ -11,6 +11,9 @@ const cachedKeys = new Set<string>()
1111
const validatedKeys = new Set<string>()
1212

1313
/**
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+
*
1417
* @param key - **the key is not supposed to be dynamic.**
1518
* @param validate - validates the cached state, if it returns false, the state will be discarded.
1619
* 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(
2326

2427
const { cache, mutate } = useSWRConfig()
2528

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+
2737
if (!validatedKeys.has(key)) {
2838
validatedKeys.add(key)
2939

@@ -48,7 +58,7 @@ export function useSWRCache(
4858
}
4959
}
5060
}
51-
}, [])
61+
}
5262
}
5363

5464
/**

0 commit comments

Comments
 (0)