All files / src/lib query-client.ts

100% Statements 10/10
100% Branches 8/8
100% Functions 4/4
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41          5x 2x       8x             13x 2x     11x               2x 2x             8x 3x    
import { QueryClient } from "@tanstack/react-query";
import { ApiError } from "./api/base";
 
/** Dispatch a custom event when a 401 is detected, so AuthContext can handle logout */
function handle401(error: unknown) {
	if (error instanceof ApiError && error.status === 401) {
		window.dispatchEvent(new CustomEvent("auth:session-expired"));
	}
}
 
export const queryClient = new QueryClient({
	defaultOptions: {
		queries: {
			staleTime: 1000 * 60 * 5, // 5 minutes - data fresh for 5 min
			gcTime: 1000 * 60 * 30, // 30 minutes (cache garbage collection)
			retry: (failureCount, error) => {
				// Don't retry on auth errors (401/403)
				if (error instanceof ApiError && [401, 403].includes(error.status)) {
					return false;
				}
				// Retry up to 2 times for network/server errors
				return failureCount < 2;
			},
			refetchOnWindowFocus: true, // Refresh data when user returns to tab
			refetchOnReconnect: true, // Refresh when internet reconnects
		},
		mutations: {
			retry: false, // Never retry mutations by default
			onError: (error) => {
				console.error("Mutation error:", error);
				handle401(error);
			},
		},
	},
});
 
// Global query error handler for 401 detection
queryClient.getQueryCache().config.onError = (error) => {
	handle401(error);
};