import { useMemo } from "react"; import { keepPreviousData, useInfiniteQuery } from "@tanstack/react-query"; import type { HistoryPage } from "./api"; /** A history list read a page at a time, newest first (the server's keyset paging): the rows loaded * so far, the accounts they name, and whether there is an older page to ask for. While a filter * change loads, the previous filter's rows stay on screen (dimmed by the caller) and no older page is * offered — the cursor on screen belongs to the rows of the old filter. */ export function useHistoryList( queryKey: readonly unknown[], fetchPage: (before: string | null) => Promise>, ) { const list = useInfiniteQuery({ queryKey, queryFn: ({ pageParam }) => fetchPage(pageParam), initialPageParam: null as string | null, getNextPageParam: (last) => last.next_cursor ?? undefined, placeholderData: keepPreviousData, }); const rows = useMemo(() => list.data?.pages.flatMap((p) => p.items) ?? [], [list.data]); const accounts = useMemo( () => Object.assign({}, ...(list.data?.pages.map((p) => p.accounts) ?? [])) as Record< string, string >, [list.data], ); return { list, rows, accounts, hasOlder: !list.isPlaceholderData && list.hasNextPage }; } export type HistoryList = ReturnType>;