|
| 1 | +import { MutationCache, QueryCache, QueryClient } from "@tanstack/react-query"; |
| 2 | + |
| 3 | +const calculateRetryDelay = (attemptIndex: number): number => { |
| 4 | + return Math.min(1000 * 2 ** attemptIndex, 30000); |
| 5 | +}; |
| 6 | + |
| 7 | +const shouldRetry = (failureCount: number, error: Error): boolean => { |
| 8 | + if (failureCount >= 3) { |
| 9 | + return false; |
| 10 | + } |
| 11 | + |
| 12 | + if (error.message?.includes("rejected")) { |
| 13 | + return false; |
| 14 | + } |
| 15 | + |
| 16 | + if (error.message?.includes("User rejected")) { |
| 17 | + return false; |
| 18 | + } |
| 19 | + |
| 20 | + return true; |
| 21 | +}; |
| 22 | + |
| 23 | +const logError = (error: Error, context?: string): void => { |
| 24 | + const errorContext = context ? `[${context}]` : ""; |
| 25 | + console.error(`React Query Error ${errorContext}:`, { |
| 26 | + message: error.message, |
| 27 | + stack: error.stack, |
| 28 | + name: error.name, |
| 29 | + }); |
| 30 | +}; |
| 31 | + |
| 32 | +export const createQueryClient = (): QueryClient => { |
| 33 | + const queryCache = new QueryCache({ |
| 34 | + onError: (error) => { |
| 35 | + logError(error, "Query"); |
| 36 | + }, |
| 37 | + }); |
| 38 | + |
| 39 | + const mutationCache = new MutationCache({ |
| 40 | + onError: (error) => { |
| 41 | + logError(error, "Mutation"); |
| 42 | + }, |
| 43 | + }); |
| 44 | + |
| 45 | + return new QueryClient({ |
| 46 | + queryCache, |
| 47 | + mutationCache, |
| 48 | + defaultOptions: { |
| 49 | + queries: { |
| 50 | + retry: (failureCount, error) => { |
| 51 | + return shouldRetry(failureCount, error as Error); |
| 52 | + }, |
| 53 | + retryDelay: calculateRetryDelay, |
| 54 | + staleTime: 60000, |
| 55 | + gcTime: 5 * 60 * 1000, |
| 56 | + refetchOnWindowFocus: false, |
| 57 | + refetchOnReconnect: true, |
| 58 | + }, |
| 59 | + mutations: { |
| 60 | + retry: (failureCount, error) => { |
| 61 | + return shouldRetry(failureCount, error as Error); |
| 62 | + }, |
| 63 | + retryDelay: calculateRetryDelay, |
| 64 | + }, |
| 65 | + }, |
| 66 | + }); |
| 67 | +}; |
0 commit comments