Skip to content

Commit c712631

Browse files
author
Simen Owesen-Lein
authored
bugfix: make suspense and revalidateIfStale work together (#1851)
* bugfix: make suspense and revalidateIfStale work together * test: add test for revalidateIfStale used with suspense
1 parent f24c621 commit c712631

File tree

2 files changed

+33
-7
lines changed

2 files changed

+33
-7
lines changed

src/use-swr.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,13 +97,14 @@ export const useSWRHandler = <Data = any, Error = any>(
9797
// If it's paused, we skip revalidation.
9898
if (getConfig().isPaused()) return false
9999

100-
return suspense
101-
? // Under suspense mode, it will always fetch on render if there is no
102-
// stale data so no need to revalidate immediately on mount again.
103-
!isUndefined(data)
104-
: // If there is no stale data, we need to revalidate on mount;
105-
// If `revalidateIfStale` is set to true, we will always revalidate.
106-
isUndefined(data) || config.revalidateIfStale
100+
// Under suspense mode, it will always fetch on render if there is no
101+
// stale data so no need to revalidate immediately on mount again.
102+
// If data exists, only revalidate if `revalidateIfStale` is true.
103+
if (suspense) return isUndefined(data) ? false : config.revalidateIfStale
104+
105+
// If there is no stale data, we need to revalidate on mount;
106+
// If `revalidateIfStale` is set to true, we will always revalidate.
107+
return isUndefined(data) || config.revalidateIfStale
107108
}
108109

109110
// Resolve the current validating state.

test/use-swr-suspense.test.tsx

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,31 @@ describe('useSWR - suspense', () => {
163163
await screen.findByText('hello, error') // get error with cache
164164
})
165165

166+
it('should not fetch when cached data is present and `revalidateIfStale` is false', async () => {
167+
const key = createKey()
168+
mutate(key, 'cached')
169+
170+
let fetchCount = 0
171+
172+
function Section() {
173+
const { data } = useSWR(key, () => createResponse(++fetchCount), {
174+
suspense: true,
175+
revalidateIfStale: false
176+
})
177+
return <div>{data}</div>
178+
}
179+
180+
renderWithGlobalCache(
181+
<Suspense fallback={<div>fallback</div>}>
182+
<Section />
183+
</Suspense>
184+
)
185+
186+
screen.getByText('cached')
187+
await act(() => sleep(50)) // Wait to confirm fetch is not triggered
188+
expect(fetchCount).toBe(0)
189+
})
190+
166191
it('should pause when key changes', async () => {
167192
const renderedResults = []
168193
const initialKey = createKey()

0 commit comments

Comments
 (0)