skipToken
Apollo Client API reference
skipToken
skipToken provides a type-safe mechanism to skip query execution. It is currently supported with useQuery, useSuspenseQuery and useBackgroundQuery.
When you pass a skipToken to one of the supported hooks instead of the options object, the hook will not cause any requests or suspenseful behavior and keeps the last data available. It is typically used conditionally to start query execution when the input data is available.
1import { skipToken, useQuery } from "@apollo/client/react";
2
3const { data } = useQuery(query, id ? { variables: { id } } : skipToken);1import { skipToken, useSuspenseQuery } from "@apollo/client/react";
2const { data } = useSuspenseQuery(
3 query,
4 id ? { variables: { id } } : skipToken
5);1import { skipToken, useBackgroundQuery } from "@apollo/client/react";
2const [queryRef] = useBackgroundQuery(
3 query,
4 id ? { variables: { id } } : skipToken
5);Why do we recommend skipToken over { skip: true }?
Imagine this very common scenario for skip: You want to skip your query if a certain required variable is not set. You might be tempted to write something like this:
1const { data } = useSuspenseQuery(query, {
2 variables: { id },
3 skip: !id,
4});But in that case, TypeScript will complain:
1Type 'number | undefined' is not assignable to type 'number'.
2 Type 'undefined' is not assignable to type 'number'.ts(2769)To get around that, you have to tell TypeScript to ignore the fact that id could be undefined:
1const { data } = useSuspenseQuery(query, {
2 variables: { id: id! },
3 skip: !id,
4});Alternatively, you could also use some obscure default value:
1const { data } = useSuspenseQuery(query, {
2 variables: { id: id || 0 },
3 skip: !id,
4});Both of these solutions hide a potential bug. If your skip logic becomes more complex, you might accidentally introduce a bug that causes your query to execute, even when id is still undefined. In that case, TypeScript cannot warn you about it.
Instead we recommend using skipToken. It provides type safety without the need for an obscure default value:
1const { data } = useSuspenseQuery(
2 query,
3 id ? { variables: { id } } : skipToken
4);Here it becomes apparent for TypeScript that there is a direct connection between skipping and the variables option - and it will work without unsafe workarounds.