Skip to content

Commit

Permalink
fix mutate argument for infinite (#1602)
Browse files Browse the repository at this point in the history
  • Loading branch information
shuding committed Oct 31, 2021
1 parent 5ffcd4b commit 9107172
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 10 deletions.
32 changes: 22 additions & 10 deletions infinite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,22 +168,34 @@ export const infinite = ((<Data, Error, Args extends Arguments>(

const mutate = useCallback(
(
data: Data[] | undefined | Promise<Data[]> | MutatorCallback<Data[]>,
shouldRevalidate = true
...args:
| []
| [undefined | Data[] | Promise<Data[]> | MutatorCallback<Data[]>]
| [
undefined | Data[] | Promise<Data[]> | MutatorCallback<Data[]>,
boolean
]
) => {
const data = args[0]

// Default to true.
const shouldRevalidate = args[1] !== false

// It is possible that the key is still falsy.
if (!contextCacheKey) return

if (shouldRevalidate && !isUndefined(data)) {
// We only revalidate the pages that are changed
const originalData = dataRef.current
cache.set(contextCacheKey, [false, originalData])
} else if (shouldRevalidate) {
// Calling `mutate()`, we revalidate all pages
cache.set(contextCacheKey, [true])
if (shouldRevalidate) {
if (!isUndefined(data)) {
// We only revalidate the pages that are changed
const originalData = dataRef.current
cache.set(contextCacheKey, [false, originalData])
} else {
// Calling `mutate()`, we revalidate all pages
cache.set(contextCacheKey, [true])
}
}

return swr.mutate(data, shouldRevalidate)
return args.length ? swr.mutate(data, shouldRevalidate) : swr.mutate()
},
// swr.mutate is always the same reference
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
30 changes: 30 additions & 0 deletions test/use-swr-infinite.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -954,4 +954,34 @@ describe('useSWRInfinite', () => {
await nextTick()
screen.getByText('data:fallback-1,fallback-2')
})

it('should revalidate the resource with bound mutate when no argument is passed', async () => {
let t = 0
const key = createKey()
const fetcher = jest.fn(async () =>
createResponse(`foo-${t++}`, { delay: 10 })
)
const logger = []
function Page() {
const { data, mutate } = useSWRInfinite(() => key, fetcher, {
dedupingInterval: 0
})
logger.push(data)
return (
<>
<div>data: {String(data)}</div>
<button onClick={() => mutate()}>mutate</button>
</>
)
}

renderWithConfig(<Page />)
await screen.findByText('data: foo-0')

fireEvent.click(screen.getByText('mutate'))
await screen.findByText('data: foo-1')
expect(fetcher).toBeCalledTimes(2)

expect(logger).toEqual([undefined, ['foo-0'], ['foo-1']])
})
})

0 comments on commit 9107172

Please sign in to comment.