Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bugfix: make suspense and revalidateIfStale work together #1851

Merged
merged 2 commits into from Feb 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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