Capítulo 40 de 80
Registering a queryFn on the QueryClient's defaultOptions.queries lets every query in the app be defined by just its queryKey — a common pattern when a single generic fetcher (e.g. one hitting a REST base URL with the key as the path) can serve most of the app.
queryFn inside new QueryClient({ defaultOptions: { queries: { queryFn: defaultQueryFn } } }) — defaultQueryFn receives the same QueryFunctionContext (including queryKey) any query function would.useQuery({ queryKey: ['/posts'] }) needs no queryFn at all once a default is registered; the key doubles as the request path/identifier in this pattern.queryFn to bypass the default — registering a default doesn't remove that option.const defaultQueryFn = async ({ queryKey }) => {
const { data } = await axios.get(`https://api.example.com${queryKey[0]}`)
return data
}
const queryClient = new QueryClient({
defaultOptions: { queries: { queryFn: defaultQueryFn } },
})
// No queryFn needed — the key IS the request
function Posts() {
const { data } = useQuery({ queryKey: ['/posts'] })
}
useQuery call site into just a key.queryFn per call to override when needed.queryFn contract this default still has to satisfy.defaultOptions lives.