umami/src/components/hooks/usePagedQuery.ts
2025-02-13 22:53:25 -08:00

31 lines
859 B
TypeScript

import { UseQueryOptions } from '@tanstack/react-query';
import { useState } from 'react';
import { PageResult, PageParams, PagedQueryResult } from '@/lib/types';
import { useApi } from './useApi';
import { useNavigation } from './useNavigation';
export function usePagedQuery<T = any>({
queryKey,
queryFn,
...options
}: Omit<UseQueryOptions, 'queryFn'> & { queryFn: (params?: object) => any }): PagedQueryResult<T> {
const { query: queryParams } = useNavigation();
const [params, setParams] = useState<PageParams>({
search: '',
page: +queryParams.page || 1,
});
const { useQuery } = useApi();
const { data, ...query } = useQuery({
queryKey: [{ ...queryKey, ...params }],
queryFn: () => queryFn(params as any),
...options,
});
return {
result: data as PageResult<T>,
query,
params,
setParams,
};
}