diff --git a/src/use-swr-infinite.ts b/src/use-swr-infinite.ts index e15937b1e..8b62b868d 100644 --- a/src/use-swr-infinite.ts +++ b/src/use-swr-infinite.ts @@ -5,6 +5,7 @@ import SWRConfigContext from './swr-config-context' import useSWR from './use-swr' import { keyType, fetcherFn, ConfigInterface, responseInterface } from './types' + type KeyLoader = ( index: number, previousPageData: Data | null @@ -151,7 +152,7 @@ function useSWRInfinite( const shouldRevalidatePage = revalidateAll || force || - (typeof force === 'undefined' && i === 0) || + (typeof force === 'undefined' && i === 0 && originalData) || (originalData && !config.compare(originalData[i], pageData)) || typeof pageData === 'undefined' diff --git a/test/use-swr-infinite.test.tsx b/test/use-swr-infinite.test.tsx index 66f501659..17fe8d036 100644 --- a/test/use-swr-infinite.test.tsx +++ b/test/use-swr-infinite.test.tsx @@ -6,7 +6,7 @@ import { act } from '@testing-library/react' -import { useSWRInfinite } from '../src' +import { useSWRInfinite, mutate } from '../src' describe('useSWRInfinite', () => { it('should render the first page component', async () => { @@ -59,7 +59,7 @@ describe('useSWRInfinite', () => { let pageData = ['apple', 'banana', 'pineapple'] function Page() { - const { data, mutate } = useSWRInfinite( + const { data, mutate: boundMutate } = useSWRInfinite( index => [`pagetest-3`, index], async (_, index) => { await new Promise(res => setTimeout(res, 100)) @@ -74,7 +74,7 @@ describe('useSWRInfinite', () => {
{ // reload the entire list - mutate() + boundMutate() }} > {data} @@ -441,4 +441,26 @@ describe('useSWRInfinite', () => { expect(setSize).toEqual(setters[0]) } }) + + it('should share initial cache from `useSWR`', async () => { + const cachedData = new Date().toISOString() + mutate('shared-cache-0', cachedData) + + function Page() { + const { data } = useSWRInfinite( + index => `shared-cache-${index}`, + async () => { + await new Promise(res => setTimeout(res, 200)) + return cachedData + } + ) + + return
{data}
+ } + const { container } = render() + expect(container.textContent).toMatchInlineSnapshot(`""`) + // after a rerender we should already have the cached data rendered + await act(() => new Promise(res => setTimeout(res, 10))) + expect(container.textContent).toMatchInlineSnapshot(`"${cachedData}"`) + }) })