Skip to content

Commit 540a449

Browse files
authored
fix: data passed to refreshInterval function is not latest (#2354)
1 parent bb55887 commit 540a449

2 files changed

Lines changed: 42 additions & 1 deletion

File tree

core/use-swr.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -591,7 +591,7 @@ export const useSWRHandler = <Data = any, Error = any>(
591591
// Use the passed interval
592592
// ...or invoke the function with the updated data to get the interval
593593
const interval = isFunction(refreshInterval)
594-
? refreshInterval(data)
594+
? refreshInterval(getCache().data)
595595
: refreshInterval
596596

597597
// We only start the next interval if `refreshInterval` is not 0, and:

test/use-swr-refresh.test.tsx

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,47 @@ describe('useSWR - refresh', () => {
672672
screen.getByText('count: 4')
673673
})
674674

675+
it('should pass updated data to refreshInterval, when refreshInterval is constant function', async () => {
676+
let count = 1
677+
678+
// constant function
679+
const refreshInterval = jest.fn(updatedCount => {
680+
return updatedCount > 5 ? 0 : 1000
681+
})
682+
683+
const key = createKey()
684+
function Page() {
685+
// constant function
686+
// const refreshInterval = useCallback((updatedCount) => {
687+
// return updatedCount > 5 ? 0 : 1000
688+
// }, [])
689+
690+
const { data } = useSWR(key, () => count++, {
691+
refreshInterval,
692+
dedupingInterval: 100
693+
})
694+
return <div>count: {data}</div>
695+
}
696+
697+
renderWithConfig(<Page />)
698+
699+
// hydration
700+
screen.getByText('count:')
701+
702+
// mount
703+
await screen.findByText('count: 1')
704+
705+
await act(() => advanceTimers(1000))
706+
screen.getByText('count: 2')
707+
expect(refreshInterval).toHaveBeenLastCalledWith(2)
708+
await act(() => advanceTimers(1000))
709+
screen.getByText('count: 3')
710+
expect(refreshInterval).toHaveBeenLastCalledWith(3)
711+
await act(() => advanceTimers(1000))
712+
screen.getByText('count: 4')
713+
expect(refreshInterval).toHaveBeenLastCalledWith(4)
714+
})
715+
675716
it('should disable refresh if function returns 0', async () => {
676717
let count = 1
677718

0 commit comments

Comments
 (0)