Skip to content

Commit

Permalink
fix: supprt multiple useSWRInfinite hooks in a page
Browse files Browse the repository at this point in the history
  • Loading branch information
koba04 committed Mar 6, 2021
1 parent cc69810 commit 16ac68f
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions src/use-swr-infinite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ function useSWRInfinite<Data = any, Error = any>(
)
let {
initialSize = 1,
revalidateAll = false,
// should revalidate pages when a refresh timer is invoked
revalidateAll = !!config.refreshInterval,
persistSize = false,
fetcher: defaultFetcher,
...extraConfig
Expand Down Expand Up @@ -117,10 +118,11 @@ function useSWRInfinite<Data = any, Error = any>(

// keep the data inside a ref
const dataRef = useRef<Data[]>()
const lastFetchedDataRef = useRef<Data[]>()

// actual swr of all pages
const swr = useSWR<Data[], Error>(
firstPageKey ? ['many', firstPageKey] : null,
firstPageKey ? ['many', firstPageKey, pageCountRef.current] : null,
async () => {
// get the revalidate context
const { originalData, force } = cache.get(contextCacheKey) || {}
Expand All @@ -146,15 +148,11 @@ function useSWRInfinite<Data = any, Error = any>(
// - `revalidateAll` is enabled
// - `mutate()` called
// - the cache is missing
// - it's the first page and it's not the first render
// - cache has changed
const shouldFetchPage =
revalidateAll ||
force ||
typeof pageData === 'undefined' ||
(typeof force === 'undefined' &&
i === 0 &&
typeof dataRef.current !== 'undefined') ||
(originalData && !config.compare(originalData[i], pageData))

if (shouldFetchPage) {
Expand All @@ -168,6 +166,7 @@ function useSWRInfinite<Data = any, Error = any>(

data.push(pageData)
previousPageData = pageData
lastFetchedDataRef.current = data
}

// once we executed the data fetching based on the context, clear the context
Expand All @@ -176,7 +175,11 @@ function useSWRInfinite<Data = any, Error = any>(
// return the data
return data
},
extraConfig
// do not pass initialData for updating to revalidate
{
...extraConfig,
initialData: didMountRef.current ? undefined : extraConfig.initialData
}
)

// update dataRef
Expand Down Expand Up @@ -213,9 +216,8 @@ function useSWRInfinite<Data = any, Error = any>(
}
cache.set(pageCountCacheKey, pageCountRef.current)
rerender(v => !v)
return mutate(v => v)
},
[mutate, pageCountCacheKey]
[pageCountCacheKey]
)

// Use getter functions to avoid unnecessary re-renders caused by triggering all the getters of the returned swr object
Expand All @@ -226,7 +228,9 @@ function useSWRInfinite<Data = any, Error = any>(
enumerable: true
},
data: {
get: () => swr.data,
get: () =>
// return the last data when revalidating
swr.data !== undefined ? swr.data : lastFetchedDataRef.current,
enumerable: true
},
// revalidate will be deprecated in the 1.x release
Expand Down

0 comments on commit 16ac68f

Please sign in to comment.