skipToken
Apollo Client API reference
skipToken
skipToken provides a type-safe mechanism to skip query execution. It is currently supported with 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.
JavaScript
Recommended usage of skipToken with useSuspenseQuery
1import { skipToken, useSuspenseQuery } from "@apollo/client/react";
2const { data } = useSuspenseQuery(
3 query,
4 id ? { variables: { id } } : skipToken
5);JavaScript
Recommended usage of skipToken with useBackgroundQuery
1import { skipToken, useBackgroundQuery } from "@apollo/client/react";
2const [queryRef] = useBackgroundQuery(
3 query,
4 id ? { variables: { id } } : skipToken
5);Note: Why do we recommendskipTokenover{ skip: true }?Imagine this very common scenario forskip: You want to skip your query if a certain required variable is not set. You might be tempted to write something like this:But in that case, TypeScript will complain:TypeScript1const { data } = useSuspenseQuery(query, { 2 variables: { id }, 3 skip: !id, 4});To get around that, you have to tell TypeScript to ignore the fact thatText1Type 'number | undefined' is not assignable to type 'number'. 2 Type 'undefined' is not assignable to type 'number'.ts(2769)idcould beundefined:Alternatively, you could also use some obscure default value:TypeScript1const { data } = useSuspenseQuery(query, { 2 variables: { id: id! }, 3 skip: !id, 4});Both of these solutions hide a potential bug. If yourTypeScript1const { data } = useSuspenseQuery(query, { 2 variables: { id: id || 0 }, 3 skip: !id, 4});skiplogic becomes more complex, you might accidentally introduce a bug that causes your query to execute, even whenidis stillundefined. In that case, TypeScript cannot warn you about it.Instead we recommend usingskipToken. It provides type safety without the need for an obscure default value:Here it becomes apparent for TypeScript that there is a direct connection between skipping and theTypeScript1const { data } = useSuspenseQuery( 2 query, 3 id ? { variables: { id } } : skipToken 4);variablesoption - and it will work without unsafe workarounds.