Skip to content

Commit

Permalink
[Infinite] Return current data if failed to resolve pages from cache …
Browse files Browse the repository at this point in the history
…when setting size (#1379)
  • Loading branch information
shuding authored Aug 25, 2021
1 parent b02d743 commit 96b49a8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
12 changes: 7 additions & 5 deletions infinite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ export const infinite = ((<Data, Error>(useSWRNext: SWRHook) => (

const mutate = useCallback(
(
data: Data[] | Promise<Data[]> | MutatorCallback<Data[]>,
data: Data[] | undefined | Promise<Data[]> | MutatorCallback<Data[]>,
shouldRevalidate = true
) => {
// It is possible that the key is still falsy.
Expand All @@ -185,23 +185,25 @@ export const infinite = ((<Data, Error>(useSWRNext: SWRHook) => (
)

// Function to load pages data from the cache based on the page size.
const resolvePagesFromCache = (pageSize: number): Data[] => {
const resolvePagesFromCache = (pageSize: number): Data[] | undefined => {
// return an array of page data
const data: Data[] = []

let previousPageData = null
for (let i = 0; i < pageSize; ++i) {
const [pageKey] = serialize(getKey ? getKey(i, previousPageData) : null)

// Get the cached page data. Skip if we can't get it from the cache.
// Get the cached page data.
const pageData = pageKey ? cache.get(pageKey) : UNDEFINED
if (isUndefined(pageData)) break

// Return the current data if we can't get it from the cache.
if (isUndefined(pageData)) return dataRef.current

data.push(pageData)
previousPageData = pageData
}

// return the data
// Return the data
return data
}

Expand Down
23 changes: 23 additions & 0 deletions test/use-swr-infinite.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -864,4 +864,27 @@ describe('useSWRInfinite', () => {
await screen.findByText('data:response value,response value')
expect(getData).toHaveBeenCalledTimes(3)
})

it('should return fallbackData if cache is empty', async () => {
const key = createKey()

function Page() {
const { data, setSize } = useSWRInfinite<string, string>(
index => key + '-' + index,
() => sleep(30).then(() => 'response value'),
{ fallbackData: ['fallback-1', 'fallback-2'] }
)
return (
<div onClick={() => setSize(2)}>data:{data ? data.join(',') : ''}</div>
)
}
render(<Page />)

screen.getByText('data:fallback-1,fallback-2')

// Update size, it should still render the fallback
fireEvent.click(screen.getByText('data:fallback-1,fallback-2'))
await nextTick()
screen.getByText('data:fallback-1,fallback-2')
})
})

0 comments on commit 96b49a8

Please sign in to comment.