TanStackT
TanStack2y ago
20 replies
efficient-indigo

V5: Only previous pages infinite query (chat like infinite scroll)

Hello everyone,

In V4 i implemented an infinite list of messages, the previous pages were fetched when scrolling on top, like a chat app, it worked perfectly.

I was using this code: (i'm using trpc but i think my issue is more tanstack query related so i post here)
export function useInfinitePrivateMessages(input: InfinitePrivateMessagesInputs, options: { enabled?: boolean }) {
  const messagesQuery = trpc.inboxGroup.infinteInboxGroupMessages.useInfiniteQuery(input, {
    getPreviousPageParam: (lastPage) => lastPage.prevCursor,
    keepPreviousData: true,
    ...options,
  });

  return messagesQuery;
}

But now in v5, getNextPageParams is required. I tried to replace getPreviousPageParam with getNextPageParam and tweak it so i get the same behavior, but i didnt manage to. Everytime i get wrong post order since getNextPageParam is adding new page at the end and i need to add new page at the beginning so i can fetch more recent messages when scrolling top.

The only way i managed to get correct order is with this code by using only getPreviousPageParam and bypassing getNextPageParam by always returning undefined :
export function useInfinitePrivateMessages(input: InfinitePrivateMessagesInputs) {
  const messagesQuery = trpc.inboxGroup.infinteInboxGroupMessages.useInfiniteQuery(input, {
    getNextPageParam: () => undefined,
    getPreviousPageParam: (firstPage) => firstPage.prevCursor,
  });

  return messagesQuery;
}

But when i scroll to get all previous pages and the windows is refocused the content is replaced with only the last previous fetched page.

Is it possible in v5 to implements a chat like infinite scroll ? Or i am just bad and maybe someone can share me example ?

Thanks you in advance for yout help
Was this page helpful?