react-query-fetcher
v0.0.1
Published
TanStack React Query default fetcher using axios with automatic URL construction from query keys
Maintainers
Readme
tanstack-query-fetcher
A lightweight, convention-driven default fetcher for TanStack React Query that auto-constructs API URLs from query keys, powered by axios.
Why?
This package provides a drop-in default fetcher that follows a predictable convention: every segment of your query key becomes part of the URL path, and the last key (if an object) becomes query parameters. No more repetitive URL construction in every query.
Installation
npm install tanstack-query-fetcher axiosQuick Start
import { QueryClient } from "@tanstack/react-query";
import { createDefaultFetcher } from "tanstack-query-fetcher";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: createDefaultFetcher({basePath: "/api"}),
},
},
});Now your queries "just work" — the query key becomes the URL automatically.
How Query Keys Map to URLs
The library follows this convention:
| Query Key | Generated URL |
|---|---|
| ["users"] | /api/users |
| ["users", 42] | /api/users/42 |
| ["users", "posts", { page: 2 }] | /api/users/posts?page=2 |
| ["users", 42, "posts", { page: 2, sort: "desc" }] | /api/users/42/posts?page=2&sort=desc |
| ["search", { q: "hello", tags: ["js", "ts"] }] | /api/search?q=hello&tags=js&tags=ts |
Rules:
- All keys except the last are joined as path segments prefixed by
api(or your custombasePath). - The last key, if it's a plain object, is serialized as query parameters.
- The last key, if it's a string or number, is appended as a final path segment.
- Leading/trailing slashes in path segments are automatically normalized to prevent double slashes and 308 redirects.
API
createDefaultFetcher(options?)
Creates a queryFn compatible with TanStack Query's defaultQueryFn.
const defaultQueryFn = createDefaultFetcher({
basePath?: string; // default: ""
timeoutMs?: number; // default: 30_000 (30 seconds)
errorProcessor?: (error: unknown) => void;
});basePath
Set a custom base path instead of api:
createDefaultFetcher({ basePath: "v2" });
// ["users"] → /v2/userstimeoutMs
Request timeout in milliseconds (default: 30,000).
createDefaultFetcher({ timeoutMs: 10_000 }); // 10 second timeouterrorProcessor
Custom error handling callback. When provided, the library delegates all error handling to your function — it will not throw. Useful for centralized error logging, toast notifications, or redirecting on 401s.
createDefaultFetcher({
errorProcessor: (error) => {
// log to your error reporting service, show toast, etc.
console.error("Query failed:", error);
},
});Without an errorProcessor, the library throws descriptive errors by default.
Full Example
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
import { createDefaultFetcher } from "tanstack-query-fetcher";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: createDefaultFetcher({
basePath: "api/v1",
timeoutMs: 15_000,
}),
},
},
});
function App() {
return (
<QueryClientProvider client={queryClient}>
<Users />
</QueryClientProvider>
);
}
function Users() {
// This automatically fetches GET /api/v1/users/42/posts?sort=recent
const { data, isLoading } = useQuery({
queryKey: ["users", 42, "posts", { sort: "recent" }],
});
if (isLoading) return <div>Loading...</div>;
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}Error Handling
By default, the fetcher throws with descriptive messages:
"Request failed with status code 404: GET /api/users/42"— for HTTP errors with a status."Request timed out after 30s: GET /api/users"— when the request exceedstimeoutMs."Network response was not ok: GET /api/users"— for non-axios errors.
For 422 and 400 responses that include an errors property in the response body (common in validation error responses), the fetcher throws the errors object directly instead of a generic message.
License
MIT
