Skip to content

Commit 2542931

Browse files
committed
fix leaking internal state when setSize on null key
1 parent 4469c0c commit 2542931

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/use-swr-infinite.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,9 @@ function useSWRInfinite<Data = any, Error = any>(
159159

160160
const mutate = useCallback(
161161
(data: MutatorCallback, shouldRevalidate = true) => {
162+
// It is possible that the key is still falsy.
163+
if (!contextCacheKey) return undefined
164+
162165
if (shouldRevalidate && typeof data !== 'undefined') {
163166
// we only revalidate the pages that are changed
164167
const originalData = dataRef.current
@@ -178,6 +181,9 @@ function useSWRInfinite<Data = any, Error = any>(
178181
// extend the SWR API
179182
const setSize = useCallback(
180183
(arg: number | ((size: number) => number)) => {
184+
// It is possible that the key is still falsy.
185+
if (!pageSizeCacheKey) return undefined
186+
181187
let size
182188
if (typeof arg === 'function') {
183189
size = arg(resolvePageSize())

test/use-swr-infinite.test.tsx

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -544,14 +544,31 @@ describe('useSWRInfinite', () => {
544544
await screen.findByText('B:page-2-2')
545545
})
546546

547-
it.only('should support null as getKey', async () => {
547+
it('should support null as getKey', async () => {
548548
function Page() {
549-
const { data } = useSWRInfinite<string, string>(null, () => 'data')
550-
return <div>data:{data}</div>
549+
const { data, setSize } = useSWRInfinite<string, string>(
550+
null,
551+
() => 'data'
552+
)
553+
554+
return (
555+
<div
556+
onClick={() => {
557+
// load next page
558+
setSize(size => size + 1)
559+
}}
560+
>
561+
data:{data || ''}
562+
</div>
563+
)
551564
}
552565

553566
render(<Page />)
554567
screen.getByText('data:')
555568
await screen.findByText('data:')
569+
570+
// load next page
571+
fireEvent.click(screen.getByText('data:'))
572+
await screen.findByText('data:')
556573
})
557574
})

0 commit comments

Comments
 (0)