-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathusePromptVersionsByIdInfinite.ts
More file actions
55 lines (51 loc) · 1.88 KB
/
Copy pathusePromptVersionsByIdInfinite.ts
File metadata and controls
55 lines (51 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { useInfiniteQuery } from "@tanstack/react-query";
import { Sorting } from "@/types/sorting";
import { Filter } from "@/types/filters";
import {
getPromptVersionsById,
PromptVersionsByIdResponse,
} from "./getPromptVersionsById";
const PAGE_SIZE = 25;
type UsePromptVersionsByIdInfiniteParams = {
promptId: string;
sorting?: Sorting;
filters?: Filter[];
search?: string;
};
type UsePromptVersionsByIdInfiniteOptions = {
enabled?: boolean;
refetchInterval?: number;
};
export default function usePromptVersionsByIdInfinite(
params: UsePromptVersionsByIdInfiniteParams,
options?: UsePromptVersionsByIdInfiniteOptions,
) {
return useInfiniteQuery<PromptVersionsByIdResponse>({
// Shares the "prompt-versions" key prefix (and the same
// `{ promptId, ... }` params shape) with usePromptVersionsById so the
// mutation hooks that invalidate that prefix (create/delete/deploy a
// version) also invalidate this list — otherwise the sidebar goes stale
// after every write. Doesn't collide in the cache: this hook's params
// never include `page`/`size`, which usePromptVersionsById always does.
queryKey: ["prompt-versions", params],
queryFn: (context) =>
getPromptVersionsById(context, {
...params,
size: PAGE_SIZE,
page: context.pageParam as number,
}),
// `size` on the response is the actual item count returned (not the
// requested page size), so it shrinks on the last page and hits 0 past
// it — `page * size` is not a valid "items seen so far" once that
// happens. Sum each page's real content length instead.
getNextPageParam: (lastPage, allPages) => {
const fetchedCount = allPages.reduce(
(sum, p) => sum + p.content.length,
0,
);
return fetchedCount < lastPage.total ? allPages.length + 1 : undefined;
},
initialPageParam: 1,
...options,
});
}