Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix useSWRInfinite response type #584

Merged
merged 1 commit into from
Aug 5, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions src/use-swr-infinite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ type SWRInfiniteResponseInterface<Data = any, Error = any> = responseInterface<
Data[],
Error
> & {
size?: number
setSize?: (
size: number
setSize: (
size: number | ((size: number) => number)
) => Promise<Data[] | undefined>
}
Expand Down Expand Up @@ -120,7 +120,7 @@ function useSWRInfinite<Data = any, Error = any>(
}, [firstPageKey])

// actual swr of all pages
const swr: SWRInfiniteResponseInterface<Data, Error> = useSWR<Data[], Error>(
const swr = useSWR<Data[], Error>(
firstPageKey ? ['many', firstPageKey] : null,
async () => {
// get the revalidate context
Expand Down Expand Up @@ -177,14 +177,16 @@ function useSWRInfinite<Data = any, Error = any>(
extraConfig
)

const swrInfinite = swr as SWRInfiniteResponseInterface<Data, Error>

// extend the SWR API
const mutate = swr.mutate
swr.size = pageCountRef.current
swr.mutate = useCallback(
const mutate = swrInfinite.mutate
swrInfinite.size = pageCountRef.current
swrInfinite.mutate = useCallback(
(data, shouldRevalidate = true) => {
if (shouldRevalidate && typeof data !== 'undefined') {
// we only revalidate the pages that are changed
const originalData = swr.data
const originalData = swrInfinite.data
cache.set(contextCacheKey, { originalData, force: false })
} else if (shouldRevalidate) {
// calling `mutate()`, we revalidate all pages
Expand All @@ -193,9 +195,9 @@ function useSWRInfinite<Data = any, Error = any>(

return mutate(data, shouldRevalidate)
},
[mutate, swr.data, contextCacheKey]
[mutate, swrInfinite.data, contextCacheKey]
)
swr.setSize = useCallback(
swrInfinite.setSize = useCallback(
arg => {
if (typeof arg === 'function') {
pageCountRef.current = arg(pageCountRef.current)
Expand All @@ -204,12 +206,12 @@ function useSWRInfinite<Data = any, Error = any>(
}
cache.set(pageCountCacheKey, pageCountRef.current)
rerender(v => !v)
return swr.mutate(v => v)
return swrInfinite.mutate(v => v)
},
[swr.mutate, pageCountCacheKey]
[swrInfinite.mutate, pageCountCacheKey]
)

return swr
return swrInfinite
}

export {
Expand Down