Skip to content

Commit

Permalink
fix: useSWRInfinite revalidates with revalidateOnMount (#1830)
Browse files Browse the repository at this point in the history
  • Loading branch information
koba04 committed Feb 2, 2022
1 parent a4ab0c9 commit 922048e
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
8 changes: 7 additions & 1 deletion infinite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ export const infinite = (<Data, Error>(useSWRNext: SWRHook) =>
initialSize = 1,
revalidateAll = false,
persistSize = false,
revalidateFirstPage = true
revalidateFirstPage = true,
revalidateOnMount = false
} = config

// The serialized key of the first page.
Expand Down Expand Up @@ -101,6 +102,9 @@ export const infinite = (<Data, Error>(useSWRNext: SWRHook) =>
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [firstPageKey])

// Needs to check didMountRef during mounting, not in the fetcher
const shouldRevalidateOnMount = revalidateOnMount && !didMountRef.current

// Actual SWR hook to load all pages in one fetcher.
const swr = useSWRNext<Data[], Error>(
firstPageKey ? INFINITE_PREFIX + firstPageKey : null,
Expand Down Expand Up @@ -131,12 +135,14 @@ export const infinite = (<Data, Error>(useSWRNext: SWRHook) =>
// - `mutate()` called
// - the cache is missing
// - it's the first page and it's not the initial render
// - `revalidateOnMount` is enabled and it's on mount
// - cache for that page has changed
const shouldFetchPage =
revalidateAll ||
forceRevalidateAll ||
isUndefined(pageData) ||
(revalidateFirstPage && !i && !isUndefined(dataRef.current)) ||
shouldRevalidateOnMount ||
(originalData &&
!isUndefined(originalData[i]) &&
!config.compare(originalData[i], pageData))
Expand Down
40 changes: 40 additions & 0 deletions test/use-swr-infinite.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1150,4 +1150,44 @@ describe('useSWRInfinite', () => {
fireEvent.click(screen.getByText('mutate'))
await screen.findByText('data: B1,B2,B3')
})

it('should revalidate when the component is mounted and revalidateOnMount is enabled', async () => {
const key = createKey()

let counter = 0

function Content() {
const { data } = useSWRInfinite(
() => key,
() => createResponse(++counter),
{
revalidateOnMount: true,
revalidateFirstPage: false,
dedupingInterval: 0
}
)
return <div>data: {String(data)}</div>
}

function Page() {
const [contentKey, setContentKey] = useState('a')
return (
<>
<Content key={contentKey} />
<button
onClick={() => {
setContentKey('b')
}}
>
mutate
</button>
</>
)
}
renderWithConfig(<Page />)
await screen.findByText('data: 1')

fireEvent.click(screen.getByText('mutate'))
await screen.findByText('data: 2')
})
})

0 comments on commit 922048e

Please sign in to comment.