53129
Pa
PAT / files
PAT / src / hooks / api / useThreads.ts
1.0 KB
1import type { Thread } from "@/src/lib/db/schema"; 2import { useInfiniteQuery } from "@tanstack/react-query"; 3 4export type ThreadsData = { 5 threads: Thread[]; 6 hasMore: boolean; 7 totalCount: number; 8}; 9 10export function useThreads(limit: number = 8) { 11 return useInfiniteQuery<ThreadsData, Error>({ 12 queryKey: ["threads", limit], 13 queryFn: async ({ pageParam }): Promise<ThreadsData> => { 14 const requestParams = new URLSearchParams(); 15 requestParams.set("offset", pageParam ? pageParam.toString() : "0"); 16 requestParams.set("limit", limit.toString() ?? "8"); 17 const response = await fetch(`/api/threads?${requestParams.toString()}`); 18 if (!response.ok) { 19 throw new Error(`Failed to fetch threads: ${response.statusText}`); 20 } 21 return response.json(); 22 }, 23 initialPageParam: 0, 24 getNextPageParam: (lastPage, allPages) => { 25 const nextOffset = allPages.reduce((acc, page) => acc + page.threads.length, 0); 26 return lastPage.hasMore ? nextOffset : undefined; 27 }, 28 }); 29}