di usage in website
This commit is contained in:
39
apps/website/lib/di/hooks/useReactQueryWithApiError.ts
Normal file
39
apps/website/lib/di/hooks/useReactQueryWithApiError.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { UseQueryResult } from '@tanstack/react-query';
|
||||
import { ApiError } from '@/lib/api/base/ApiError';
|
||||
|
||||
/**
|
||||
* Converts React-Query error to ApiError for StateContainer compatibility
|
||||
* This eliminates the need to repeat error conversion logic in every hook
|
||||
*/
|
||||
export function convertToApiError(error: any): ApiError | null {
|
||||
if (!error) return null;
|
||||
|
||||
if (error instanceof ApiError) {
|
||||
return error;
|
||||
}
|
||||
|
||||
return new ApiError(
|
||||
error.message || 'An unexpected error occurred',
|
||||
'UNKNOWN_ERROR',
|
||||
{ timestamp: new Date().toISOString() },
|
||||
error instanceof Error ? error : undefined
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to enhance React-Query result with ApiError conversion
|
||||
* Returns the same structure as before but with DRY error handling
|
||||
*/
|
||||
export function enhanceQueryResult<TData, TError = any>(
|
||||
queryResult: UseQueryResult<TData, TError>
|
||||
) {
|
||||
const apiError = convertToApiError(queryResult.error);
|
||||
|
||||
return {
|
||||
...queryResult,
|
||||
error: apiError, // Directly return ApiError for StateContainer compatibility
|
||||
retry: async () => {
|
||||
await queryResult.refetch();
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user