Skip to content

Commit

Permalink
fix: re-render when returned data and fallbackData is the same and ke…
Browse files Browse the repository at this point in the history
…epPreviousData is enabled (#2169)

test: add a failed test for #2128
  • Loading branch information
koba04 committed Oct 4, 2022
1 parent d32607f commit ea9bb27
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
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')
})
})

0 comments on commit ea9bb27

Please sign in to comment.