I am trying to build an infinite scroll list with react-query and InfiniteScroll from 'react-infinite-scroller'. While it was rather easy to get the basic infinite list working I can't seem to figure out the next step, adding a header to the request.
As you see below I am getting a little bit desperate :) I added the token I want to use to the return value of the getNextPageParam function in order to use it in my fetchNextItems function. While this works for the second and following pages the token is not available in the initial fetch.
I also tried to add initialData to the useInfiniteScroll without any success.
I could just move the api calls to the jsx functional components and would have access to the token, but I'm sure there is a way that I am not seeing while I am just starting to play around with react-query.
Any suggestions and/or tips are welcome!
List.tsx
[...]
const idToken = useAppSelector(getIdToken)
const { data, isLoading, isError, hasNextPage, fetchNextPage } =
useInfiniteQuery(queryKey, fetchNextItems, {
getNextPageParam: lastPage => {
if (lastPage.nextPage < lastPage.totalPages)
return { idToken, page: lastPage.nextPage }
return undefined
},
//initialData: {}
})
[...]
<InfiniteScroll
hasMore={hasNextPage}
loadMore={fetchNextPage}
getScrollParent={() => document.getElementById('main')}
useWindow={false}
>
{data.pages.map(page =>
page?.data.map(item => (
<Component key={item._id} itemData={item} />
)),
)}
</InfiniteScroll>
api.ts
export const fetchNextItems = async ({
pageParam = { idToken: '', page: 0 },
}) => {
const response = await fetch(
`${URL}?$skip=${pageParam.page * limit}&$limit=${limit}`,
{
headers: new Headers({
Authentication: pageParam.idToken,
}),
},
)
const { data, total } = await response.json()
return {
data,
nextPage: pageParam.page + 1,
totalPages: Math.ceil(total / limit),
}
}