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

fix: keepPreviousData should also work in suspense #2649

Merged
merged 3 commits into from
Jun 5, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion core/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -698,8 +698,18 @@ export const useSWRHandler = <Data = any, Error = any>(
fetcherRef.current = fetcher
configRef.current = config
unmountedRef.current = false

if (isUndefined(error)) {
use(revalidate(WITH_DEDUPE))
const promise: Promise<boolean> & {
status?: 'pending' | 'fulfilled' | 'rejected'
value?: boolean
reason?: unknown
} = revalidate(WITH_DEDUPE)
if (!isUndefined(returnedData)) {
promise.status = 'fulfilled'
promise.value = true
}
use(promise as Promise<boolean>)
} else {
throw error
}
Expand Down
39 changes: 39 additions & 0 deletions test/use-swr-suspense.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { act, fireEvent, screen } from '@testing-library/react'
import type { ReactNode, PropsWithChildren } from 'react'
import { Profiler } from 'react'
import React, { Suspense, useEffect, useReducer, useState } from 'react'
import useSWR, { mutate } from 'swr'
import {
Expand Down Expand Up @@ -398,4 +399,42 @@ describe('useSWR - suspense', () => {

await screen.findByText('SWR')
})

it('should only render fallback once when `keepPreviousData` is set to true', async () => {
const originKey = createKey()
const newKey = createKey()
const onRender = jest.fn()
const Result = ({ query }: { query: string }) => {
const { data } = useSWR(query, q => createResponse(q, { delay: 200 }), {
suspense: true,
keepPreviousData: true
})
return <div>data: {data}</div>
}
const App = () => {
const [query, setQuery] = useState(originKey)
return (
<>
<button onClick={() => setQuery(newKey)}>change</button>
<br />
<Suspense
fallback={
<Profiler id={originKey} onRender={onRender}>
<div>loading</div>
</Profiler>
}
>
<Result query={query}></Result>
</Suspense>
</>
)
}
renderWithConfig(<App />)
await act(() => sleep(200))
await screen.findByText(`data: ${originKey}`)
fireEvent.click(screen.getByText('change'))
await act(() => sleep(200))
await screen.findByText(`data: ${newKey}`)
expect(onRender).toHaveBeenCalledTimes(1)
})
})