From ee290573cfa856ac538cba3feaf5ed33fe63721a Mon Sep 17 00:00:00 2001 From: devjiwonchoi Date: Thu, 27 Jul 2023 23:55:17 +0900 Subject: [PATCH 1/2] feat: add loadingMore option --- infinite/src/index.ts | 10 +++++++++- infinite/src/types.ts | 1 + 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/infinite/src/index.ts b/infinite/src/index.ts index 7fd4b6ff5..124f9341a 100644 --- a/infinite/src/index.ts +++ b/infinite/src/index.ts @@ -307,6 +307,13 @@ export const infinite = ((useSWRNext: SWRHook) => [infiniteKey, cache, mutate, resolvePageSize] ) + // Based on https://swr.vercel.app/examples/infinite-loading + const isLoadingMore = + swr.isLoading || + (resolvePageSize() > 0 && + swr.data && + typeof swr.data[resolvePageSize() - 1] === 'undefined') + // Use getter functions to avoid unnecessary re-renders caused by triggering // all the getters of the returned swr object. return { @@ -324,7 +331,8 @@ export const infinite = ((useSWRNext: SWRHook) => }, get isLoading() { return swr.isLoading - } + }, + isLoadingMore } }) as unknown as Middleware diff --git a/infinite/src/types.ts b/infinite/src/types.ts index 0ecd996f5..3b43e1950 100644 --- a/infinite/src/types.ts +++ b/infinite/src/types.ts @@ -47,6 +47,7 @@ export interface SWRInfiniteResponse setSize: ( size: number | ((_size: number) => number) ) => Promise + isLoadingMore: boolean | undefined } export interface SWRInfiniteHook { From 5fd474466645dd653fe19873e5fba5a6bd3ce595 Mon Sep 17 00:00:00 2001 From: devjiwonchoi Date: Fri, 28 Jul 2023 00:11:00 +0900 Subject: [PATCH 2/2] chore: modify examples to use `isLoadingMore` --- examples/infinite/pages/index.js | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/examples/infinite/pages/index.js b/examples/infinite/pages/index.js index 4f7378494..865b4d9b6 100644 --- a/examples/infinite/pages/index.js +++ b/examples/infinite/pages/index.js @@ -9,19 +9,16 @@ export default function App() { const [repo, setRepo] = useState('reactjs/react-a11y') const [val, setVal] = useState(repo) - const { data, error, mutate, size, setSize, isValidating } = useSWRInfinite( - (index) => - `https://api.github.com/repos/${repo}/issues?per_page=${PAGE_SIZE}&page=${ - index + 1 - }`, - fetch - ) + const { data, mutate, size, setSize, isValidating, isLoadingMore } = + useSWRInfinite( + index => + `https://api.github.com/repos/${repo}/issues?per_page=${PAGE_SIZE}&page=${ + index + 1 + }`, + fetch + ) const issues = data ? [].concat(...data) : [] - const isLoadingInitialData = !data && !error - const isLoadingMore = - isLoadingInitialData || - (size > 0 && data && typeof data[size - 1] === 'undefined') const isEmpty = data?.[0]?.length === 0 const isReachingEnd = isEmpty || (data && data[data.length - 1]?.length < PAGE_SIZE) @@ -31,7 +28,7 @@ export default function App() {
setVal(e.target.value)} + onChange={e => setVal(e.target.value)} placeholder="reactjs/react-a11y" />