@harshilrajput/universal-api-errors-react-query
v0.1.1
Published
React Query integration for universal-api-errors: parse query/mutation errors into a UniversalError, and drive React Query's retry option from real error classification instead of a fixed count.
Maintainers
Readme
@harshilrajput/universal-api-errors-react-query
React Query integration for universal-api-errors:
parse query/mutation errors into a UniversalError, and drive React Query's retry option from
real error classification instead of a fixed count.
Install
npm install @harshilrajput/universal-api-errors-react-query
# or: pnpm add @harshilrajput/universal-api-errors-react-query
# or: yarn add @harshilrajput/universal-api-errors-react-query@tanstack/react-query is an optional peer dependency — this package's types are structural, so
it works with v4 or v5 without pinning either. @harshilrajput/universal-api-errors-core comes
along automatically as a regular dependency.
useApiError
React Query doesn't transform the error your queryFn throws — query.error is still a raw
AxiosError, a Response, or whatever else. useApiError is parseError() wired to a
query/mutation result, memoized so it doesn't re-parse on every render:
import { useQuery } from '@tanstack/react-query';
import { useApiError } from '@harshilrajput/universal-api-errors-react-query';
function UserProfile({ id }: { id: string }) {
const query = useQuery({ queryKey: ['user', id], queryFn: () => fetchUser(id) });
const error = useApiError(query);
if (error?.isUnauthorized) return <RedirectToLogin />;
if (error) return <ErrorBanner message={error.message} />;
return <Profile user={query.data} />;
}Works the same way with useMutation's result.
createRetry
React Query's default retry: 3 retries any thrown error identically — including a 404 or a
validation error that will never succeed no matter how many times you ask. createRetry only
retries what UniversalError actually classifies as retryable (network failures, timeouts, rate
limits, 5xx servers), up to a limit:
import { QueryClient } from '@tanstack/react-query';
import { createRetry } from '@harshilrajput/universal-api-errors-react-query';
const client = new QueryClient({
defaultOptions: {
queries: { retry: createRetry({ maxRetries: 3 }) },
},
});Override the classification entirely with shouldRetry:
createRetry({
maxRetries: 5,
shouldRetry: (error, failureCount) => error.isNetwork || error.isTimeout,
});Everything from core, too
This package re-exports the entire
@harshilrajput/universal-api-errors-core
public API — parseError, createUniversalError, the UniversalError class, retry,
normalizeValidation, and every type — from this one import.
License
MIT
