Last active
September 6, 2023 18:45
-
-
Save ojknation/f064ecc1746d100e0f9f494bc2d808eb to your computer and use it in GitHub Desktop.
React Query infinite query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the pageParam variable is very important, it is destructured from the object react query sends as a parameter to | |
//apiFunction, pageParam contains the current page number value which is key to the infinite query pattern | |
export const apiFunction = async ({ queryKey, pageParam }) => { | |
const [, params] = queryKey; | |
const { type, status, search, id } = params; | |
// sample params | |
const newParams = new URLSearchParams(); | |
type?.forEach((t) => newParams.append('type', t)); | |
status?.forEach((s) => newParams.append('status', s)); | |
newParams.append('search', search); | |
try { | |
const response = await Api.get(`/list`, { | |
params: { ...newParams, page: pageParam ?? 1 }, | |
}); | |
return response; | |
} catch (error) { | |
return error; | |
} | |
}; | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { hasNextPage, fetchNextPage, isFetchingNextPage, data, isLoading } = | |
useInfiniteQuery( | |
[ | |
'key-name', | |
{ | |
...params | |
}, | |
], | |
aPiFunction, | |
{ | |
getNextPageParam: (lastPage, pages) => { | |
const pagesNum = lastPage?.data?.total_pages; // total_pages is subjective, your backend might return this field as total | |
if (pagesNum > pages.length) { | |
const newPage = pages.length + 1; | |
return newPage; | |
} | |
}, | |
onSuccess: (newData) => { | |
const { pages } = newData; | |
// combine data from all pages | |
const listData = pages.flatMap((x) => x.data?.results); | |
setData(listData); | |
}, | |
} | |
); | |
// you can either pass a ref to a div under your list and use an intersection observer to trigger | |
useIntersectionObserver({ | |
target: loadMoreRef, | |
onIntersect: () => fetchNextPage(), | |
enabled: hasNextPage, | |
}); | |
// You can also manually trigger fetch next page with any event of your choice | |
fetchNextPage() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment