import { handleError } from '@lumina/libs/error-handler'; import { defaultShouldDehydrateQuery, environmentManager, QueryCache, QueryClient, } from '@tanstack/react-query'; function makeQueryClient(): QueryClient { return new QueryClient({ queryCache: new QueryCache({ // The one place a failed refetch stops; a failed first load goes to its boundary instead. onError: (error, query) => { if (query.state.data !== undefined) { handleError(error, { where: 'refetch' }); } }, }), defaultOptions: { queries: { // Hydrated data isn't refetched on mount. staleTime: 60_000, // The HTTP lib already retried idempotent requests; the user retries from the fallback. retry: false, // Offline fails at once and shows the network fallback, instead of an endless skeleton. networkMode: 'offlineFirst', // A first load that fails throws to its boundary; a failed refetch keeps the data. throwOnError: (_error, query) => query.state.data === undefined, }, mutations: { networkMode: 'offlineFirst' }, dehydrate: { // Pending queries stream to the browser. shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending', // Next.js reports the real error on the server; the browser gets its digest. shouldRedactErrors: () => false, }, }, }); } let browserQueryClient: QueryClient | undefined; /** A new client for every server request; one shared client in the browser. */ export function getQueryClient(): QueryClient { if (environmentManager.isServer()) return makeQueryClient(); browserQueryClient ??= makeQueryClient(); return browserQueryClient; }