Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Queries and Keys

Query Functions

Write reliable query functions: the context object, throwing on HTTP errors, AbortSignal cancellation, default query functions and wrapping fetch or axios.

The query function (queryFn) is the only place where TanStack Query touches your server. Everything else, caching, retries, deduplication, is built around this one function. The contract is small: it returns a promise, that promise resolves with data or rejects with an error. This lesson covers what the function receives, how to fail correctly, how to support cancellation and how to avoid repeating yourself in a large app.

The contract

JavaScript
useQuery({
  queryKey: ["todos"],
  queryFn: async () => {
    const response = await fetch("/api/todos");
    if (!response.ok) throw new Error("HTTP " + response.status);
    return response.json();
  },
});

Three rules, all enforced or assumed by Query:

  1. Return a promise. async functions do this automatically.
  2. Reject to signal failure. A thrown error or a rejected promise puts the query into the error state and triggers retries.
  3. Resolve with something other than undefined. v5 treats an undefined result as an error because the cache cannot tell it apart from "no data". Return null when "nothing" is a valid answer.

fetch only rejects when the network fails. A 404 or 500 response resolves normally, so you must check response.ok yourself. Libraries such as axios reject on non-2xx statuses for you.

Wrapping fetch once

Repeating the ok check in every function is error-prone. Put it in a tiny helper:

A fetch helper that throws on bad status

The custom HttpError carries the status, so the UI (or a retry rule, see Retries and Error Handling) can react to it. fakeFetch stands in for the network so the demo runs inside the sandbox; in a real app you call fetch the same way.

The context object

Query calls your function with one argument, the query function context:

Property Meaning
queryKey The key of this query
signal An AbortSignal that fires when the request is no longer wanted
meta Optional metadata you attached to the query
client The QueryClient running the query

Pagination and infinite queries add more fields (pageParam, direction), covered later in the course.

JavaScript
queryFn: async ({ queryKey, signal }) => {
  const [, id] = queryKey;
  const res = await fetch("/api/todos/" + id, { signal });
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json();
}

Cancellation with the signal

When a query becomes unnecessary mid-flight (the key changes, the component unmounts and no other observer remains), Query can abort the request. It only does this if your function actually consumes the signal: reading signal is what tells Query that cancellation is safe. If you never touch it, the request simply finishes and its result is cached.

Aborting an in-flight request

Switch from "cats" to "dogs" while the first request is pending, then press "Show event log". The log shows that the cats request was aborted. With a real fetch(url, { signal }) the browser cancels the HTTP request in the same way, which saves bandwidth for fast typers in a search box.

An aborted query does not go to the error state. Query reverts it to its previous state, so the UI does not flash an error for a request you chose to drop. Cancelled queries also appear as AbortError only inside your own catch blocks.

Default query function

If most of your queries follow one pattern, such as "the key is the URL", you can set a default function once and leave queryFn out of each hook:

JavaScript
const defaultQueryFn = async ({ queryKey, signal }) => {
  const res = await fetch("/api" + queryKey[0], { signal });
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json();
};

const queryClient = new QueryClient({
  defaultOptions: { queries: { queryFn: defaultQueryFn } },
});

// later, in a component:
useQuery({ queryKey: ["/todos"] });

This is compact but hides the data flow; many teams prefer one explicit function per resource, shared through queryOptions (see select and queryOptions).

Errors, skipToken and disabling

Sometimes you cannot build a valid request yet, for example because an id is still undefined. Return skipToken instead of a function, and Query will not run the query:

JavaScript
import { skipToken, useQuery } from "@tanstack/react-query";

useQuery({
  queryKey: ["user", userId],
  queryFn: userId ? () => fetchUser(userId) : skipToken,
});

This is the type-safe way to express "not ready", and it is related to the enabled option that the lesson on dependent queries explains. Calling refetch() on a query using skipToken fails, which is intended: there is nothing to fetch.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A queryFn awaits fetch('/api/x') which returns status 404 and then returns response.json(). What does Query see?

    fetch only rejects on network failure. Non-2xx responses resolve, so you must throw yourself.
  2. 2. What happens if a queryFn resolves to undefined in v5?

    undefined would be indistinguishable from no data, so v5 fails the query. Return null for an empty result.
  3. 3. When can Query abort your request?

    Reading the signal opts you in to cancellation, so Query knows aborting is safe.
  4. 4. What is skipToken used for?

    Passing skipToken as queryFn disables the query in a type-safe way.

Summary

  • A queryFn returns a promise that resolves with data (never undefined) or rejects with an error.
  • Check response.ok when using fetch, ideally in one shared helper.
  • The context gives you queryKey, signal, meta and client.
  • Pass signal to fetch to let Query cancel requests that are no longer needed.
  • skipToken or enabled keep a query idle until its inputs exist.

Next: Dependent Queries