Skip to content

Commit

Permalink
bugfix: make suspense and revalidateIfStale work together (#1851)
Browse files Browse the repository at this point in the history
* bugfix: make suspense and revalidateIfStale work together

* test: add test for revalidateIfStale used with suspense
  • Loading branch information
simowe authored and shuding committed Apr 10, 2022
1 parent f24c621 commit 1ae8cc6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
15 changes: 8 additions & 7 deletions src/use-swr.ts
Expand Up @@ -97,13 +97,14 @@ export const useSWRHandler = <Data = any, Error = any>(
// If it's paused, we skip revalidation.
if (getConfig().isPaused()) return false

return suspense
? // Under suspense mode, it will always fetch on render if there is no
// stale data so no need to revalidate immediately on mount again.
!isUndefined(data)
: // If there is no stale data, we need to revalidate on mount;
// If `revalidateIfStale` is set to true, we will always revalidate.
isUndefined(data) || config.revalidateIfStale
// Under suspense mode, it will always fetch on render if there is no
// stale data so no need to revalidate immediately on mount again.
// If data exists, only revalidate if `revalidateIfStale` is true.
if (suspense) return isUndefined(data) ? false : config.revalidateIfStale

// If there is no stale data, we need to revalidate on mount;
// If `revalidateIfStale` is set to true, we will always revalidate.
return isUndefined(data) || config.revalidateIfStale
}

// Resolve the current validating state.
Expand Down
25 changes: 25 additions & 0 deletions test/use-swr-suspense.test.tsx
Expand Up @@ -163,6 +163,31 @@ describe('useSWR - suspense', () => {
await screen.findByText('hello, error') // get error with cache
})

it('should not fetch when cached data is present and `revalidateIfStale` is false', async () => {
const key = createKey()
mutate(key, 'cached')

let fetchCount = 0

function Section() {
const { data } = useSWR(key, () => createResponse(++fetchCount), {
suspense: true,
revalidateIfStale: false
})
return <div>{data}</div>
}

renderWithGlobalCache(
<Suspense fallback={<div>fallback</div>}>
<Section />
</Suspense>
)

screen.getByText('cached')
await act(() => sleep(50)) // Wait to confirm fetch is not triggered
expect(fetchCount).toBe(0)
})

it('should pause when key changes', async () => {
const renderedResults = []
const initialKey = createKey()
Expand Down

0 comments on commit 1ae8cc6

Please sign in to comment.