Reputation: 1
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),
}
}
Upvotes: 0
Views: 1575
Reputation: 28988
Authentication is something you should likely handle outside of react-query. Just imagine how you would add a header param to a fetch request if you wouldn't use react-query?
What many people do is get the token after login, then distribute it in the app via a dedicated react context. Then, the custom react query hook can pick it up and forward it to fetch
.
If you are using libraries like axios
or ky
to do the actual data fetching, there are other ways to hook into the lifecycle of that api layer to add header parameters.
Upvotes: 0