Skip to content

Commit

Permalink
First page of useSWRInfinite should reuse the cache from useSWR (#799)
Browse files Browse the repository at this point in the history
* fix type error

* simplify code
  • Loading branch information
shuding authored Jan 7, 2021
1 parent 62ccce3 commit 62d5cfa
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
3 changes: 2 additions & 1 deletion src/use-swr-infinite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import SWRConfigContext from './swr-config-context'
import useSWR from './use-swr'

import { keyType, fetcherFn, ConfigInterface, responseInterface } from './types'

type KeyLoader<Data = any> = (
index: number,
previousPageData: Data | null
Expand Down Expand Up @@ -151,7 +152,7 @@ function useSWRInfinite<Data = any, Error = any>(
const shouldRevalidatePage =
revalidateAll ||
force ||
(typeof force === 'undefined' && i === 0) ||
(typeof force === 'undefined' && i === 0 && originalData) ||
(originalData && !config.compare(originalData[i], pageData)) ||
typeof pageData === 'undefined'

Expand Down
28 changes: 25 additions & 3 deletions test/use-swr-infinite.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -59,7 +59,7 @@ describe('useSWRInfinite', () => {
let pageData = ['apple', 'banana', 'pineapple']

function Page() {
const { data, mutate } = useSWRInfinite<string, string>(
const { data, mutate: boundMutate } = useSWRInfinite<string, string>(
index => [`pagetest-3`, index],
async (_, index) => {
await new Promise(res => setTimeout(res, 100))
Expand All @@ -74,7 +74,7 @@ describe('useSWRInfinite', () => {
<div
onClick={() => {
// reload the entire list
mutate()
boundMutate()
}}
>
{data}
Expand Down Expand Up @@ -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<string, string>(
index => `shared-cache-${index}`,
async () => {
await new Promise(res => setTimeout(res, 200))
return cachedData
}
)

return <div>{data}</div>
}
const { container } = render(<Page />)
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}"`)
})
})

0 comments on commit 62d5cfa

Please sign in to comment.