39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
import { QueryKey, UseQueryOptions, useSuspenseQuery } from "@tanstack/react-query";
|
|
import { ServerResult } from "../types";
|
|
import toast from '@/lib/sonner'
|
|
import { handleQueryError } from '../utils/global-error-handler';
|
|
|
|
export function useServerSuspenseQuery<TData>(
|
|
options: {
|
|
queryKey: QueryKey,
|
|
queryFn: () => Promise<ServerResult<TData>>;
|
|
options?: Omit<UseQueryOptions<TData, Error, TData>, 'queryFn' | 'queryKey'>
|
|
showErrorToast?: boolean;
|
|
enabled?: boolean;
|
|
}
|
|
) {
|
|
const { queryKey, queryFn, showErrorToast = true, options: queryOptions } = options;
|
|
const queryResult = useSuspenseQuery({
|
|
...queryOptions,
|
|
queryKey,
|
|
queryFn: async () => {
|
|
try {
|
|
const result = await queryFn();
|
|
|
|
if (!result.success) {
|
|
if (showErrorToast) {
|
|
toast.error(result.error.userMessage);
|
|
}
|
|
throw new Error(result.error.userMessage);
|
|
}
|
|
|
|
return result.data;
|
|
} catch (error: any) {
|
|
await handleQueryError(error);
|
|
throw error;
|
|
}
|
|
}
|
|
});
|
|
|
|
return queryResult;
|
|
} |