Network data loading
Fetch JSON from an HTTP endpoint and return the parsed response.
TanStack · Pipe
queryFn is the data-fetching function for a TanStack Query. It receives QueryFunctionContext and must return defined data or throw; a configured default can provide it when omitted.
queryFn is the function TanStack Query invokes to obtain data for a query. It receives QueryFunctionContext, including the query key and cancellation signal, and must resolve usable data or throw an error; it may be omitted when a default query function is configured.
(context: QueryFunctionContext<TQueryKey, TPageParam>) => TQueryFnData | Promise<TQueryFnData>| Name | Type | Description |
|---|---|---|
context | QueryFunctionContext<TQueryKey, TPageParam> | Context containing the query key, page parameter when applicable, and other query execution context. |
TQueryFnData or Promise<TQueryFnData>; successful results must be defined, while failures should throw.
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string }
async function fetchTodos({ signal }: { signal: AbortSignal }): Promise<Todo[]> {
const response = await fetch('/api/todos', { signal })
if (!response.ok) throw new Error('Request failed')
return response.json()
}
export function Todos() {
const query = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
return <pre>{JSON.stringify(query.data ?? [], null, 2)}</pre>
}The query function receives a context object, uses its abort signal for the request, and resolves parsed data or throws when the response fails.
Fetch JSON from an HTTP endpoint and return the parsed response.
Use query context values to select the resource or pass cancellation to a request.
Share a standard fetching implementation through QueryClient defaults.
queryFn is the function used to request a query's data. It receives QueryFunctionContext and must return data asynchronously or throw an error; the resolved value must not be undefined.
Follow-up: What can make queryFn optional? A default query function configured with setQueryDefaults or setDefaultOptions can supply it when the query does not define one.
The function receives QueryFunctionContext rather than only the query key. This context lets the implementation use query metadata such as the key and request cancellation signal.
Follow-up: How should a fetch-based query function handle cancellation? Pass the context's signal to the request so cancellation can propagate to the underlying fetch.
A queryFn can be supplied directly in query options or inherited from query defaults. The option is required when no default query function is available.
Follow-up: Does the same rule apply across QueryClient fetching APIs? Query options are shared by observers and QueryClient methods, so the configured query function is used wherever those options apply.
QueryFunctionContextQueryOptionsuseQueryQueryClientsetQueryDefaultssetDefaultOptions