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.

JavaScript
Recommended usage of skipToken with useQuery
1import { skipToken, useQuery } from "@apollo/client/react";
2
3const { data } = useQuery(query, id ? { variables: { id } } : skipToken);
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);

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:

TypeScript
1const { data } = useSuspenseQuery(query, {
2  variables: { id },
3  skip: !id,
4});

But in that case, TypeScript will complain:

Text
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:

TypeScript
1const { data } = useSuspenseQuery(query, {
2  variables: { id: id! },
3  skip: !id,
4});

Alternatively, you could also use some obscure default value:

TypeScript
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:

TypeScript
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.

Feedback

Edit on GitHub

Ask Community