T
TanStack14mo ago
noble-gold

useInfiniteQuery with maxPages considers empty data a page and removes a full page

I'm using useInfiniteQuery to get more messages as the user scrolls up, sort of like discord. now my backend does not tell me if there are more messages to fetch after I request them. It just gives me an array of messages before a specified message id. now, the getPreviousPageParam will not know if there are more pages. So what I've done is to will fetch the previous page but then if the data is empty, it will prevent further fetching.
getPreviousPageParam(_last, all) {
const earliestMessage = all[0]?.[0];
return earliestMessage ? { before: earliestMessage.id, after: "" } : undefined;
},
getPreviousPageParam(_last, all) {
const earliestMessage = all[0]?.[0];
return earliestMessage ? { before: earliestMessage.id, after: "" } : undefined;
},
but this will cause an empty array to be in the data.pages which will count as a valid page and maxPages will remove a page and replace it with this empty page. here is how that looks: [ ["some messages"] , ["some messages"] , [/*empty array*/] ] How do I tell it to not remove a page or to not even consider an empty array a page?
3 Replies
exotic-emerald
exotic-emerald14mo ago
I've run into the same problem, not yet sure of the correct solution but I have a quick idea to start with. In the queryFn you can check whether the data coming from the server is an empty list, if it is, you can throw an Error instead of returning the data. In this case the empty list won't appear in the cached data. Of course you have to deal with the error state of the useInfiniteQuery. An other quick idea: In the getPrevPageParam (and also the getNextPageParam) function don't simply check if the returned data is empty, but rather that the length of the returned data is less than the given items_per_page value. If it's less, then you can be sure that there are no more pages.
noble-gold
noble-goldOP14mo ago
The first solution might just work... The second one is what I just came up yesterday but there is a chance that the number of remaining messages matches the batch size
equal-aqua
equal-aqua14mo ago
Hmm you could set maxPages to one more than you want and never render the last page. Ideally the backend could expose that information though

Did you find this page helpful?