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: re-render when returned data and fallbackData is the same and keepPreviousData is enabled #2169

Merged
merged 3 commits into from
Oct 4, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion core/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export const useSWRHandler = <Data = any, Error = any>(
const t = _ as keyof StateDependencies
if (!compare(current[t], prev[t])) {
if (t === 'data' && isUndefined(prev[t])) {
if (!compare(current[t], fallback)) {
if (!compare(current[t], returnedData)) {
equal = false
}
} else {
Expand Down
40 changes: 40 additions & 0 deletions test/use-swr-laggy.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,44 @@ describe('useSWR - keep previous data', () => {
[key3, key3]
])
})

// https://github.com/vercel/swr/issues/2128
it('should re-render when returned data and fallbackData is the same and keepPreviousData is enabled', async () => {
const fallbackData = 'initial'
const fetcher = k => createResponse(k, { delay: 50 })
const keys = ['initial', 'updated']
function App() {
const [count, setCount] = useState(0)
const { data } = useSWR(keys[count % 2 === 0 ? 0 : 1], fetcher, {
fallbackData,
keepPreviousData: true,
revalidateOnMount: false,
revalidateOnFocus: false
})
return (
<>
<button onClick={() => setCount(c => c + 1)}>change key</button>
<div>{data}</div>
</>
)
}

renderWithConfig(<App />)
// fallbackData
screen.getByText('initial')

fireEvent.click(screen.getByText('change key'))
await act(() => sleep(10))
// previous data
screen.getByText('initial')
await act(() => sleep(100))
screen.getByText('updated')

fireEvent.click(screen.getByText('change key'))
await act(() => sleep(10))
// previous data
screen.getByText('updated')
await act(() => sleep(100))
screen.getByText('initial')
})
})