diff --git a/infinite/index.ts b/infinite/index.ts index 505fcc993..eac8d06c0 100644 --- a/infinite/index.ts +++ b/infinite/index.ts @@ -48,7 +48,8 @@ export const infinite = ((useSWRNext: SWRHook) => initialSize = 1, revalidateAll = false, persistSize = false, - revalidateFirstPage = true + revalidateFirstPage = true, + revalidateOnMount = false } = config // The serialized key of the first page. @@ -101,6 +102,9 @@ export const infinite = ((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( firstPageKey ? INFINITE_PREFIX + firstPageKey : null, @@ -131,12 +135,14 @@ export const infinite = ((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)) diff --git a/test/use-swr-infinite.test.tsx b/test/use-swr-infinite.test.tsx index 85558ae04..9cbbc57d2 100644 --- a/test/use-swr-infinite.test.tsx +++ b/test/use-swr-infinite.test.tsx @@ -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
data: {String(data)}
+ } + + function Page() { + const [contentKey, setContentKey] = useState('a') + return ( + <> + + + + ) + } + renderWithConfig() + await screen.findByText('data: 1') + + fireEvent.click(screen.getByText('mutate')) + await screen.findByText('data: 2') + }) })