useSuspenseQuery (apollo)
useQuery (apollo)のSuspense対応版
docs
https://www.apollographql.com/docs/react/data/suspense
例
code:ts
import { Suspense } from "react";
import { gql, TypedDocumentNode } from "@apollo/client";
import { useSuspenseQuery } from "@apollo/client/react";
interface Data {
dog: {
id: string;
name: string;
};
}
interface Variables {
id: string;
}
interface DogProps {
id: string;
}
const GET_DOG_QUERY: TypedDocumentNode<Data, Variables> = gql`
query GetDog($id: String) {
dog(id: $id) {
# By default, an object's cache key is a combination of
# its __typename and id fields, so we should always make
# sure the id is in the response so our data can be
# properly cached.
id
name
breed
}
}
`;
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Dog id="3" />
</Suspense>
);
}
function Dog({ id }: DogProps) {
const { data } = useSuspenseQuery(GET_DOG_QUERY, {
variables: { id },
});
return <>Name: {data.dog.name}</>;
}
gpt-5.icon
options
code:ts
const { data } = useSuspenseQuery(query, {
variables: { ... },
fetchPolicy: "cache-first",
errorPolicy: "none",
context: { ... },
queryKey: "unique-key",
});
variables (apollo)
fetchPolicy (apollo)
errorPolicy (apollo)
4. context
型: DefaultContext
説明:
Apollo Link に渡す追加情報(例: ヘッダーやメタデータ)を指定します。
認証トークンを上書きしたり、カスタム Link にデータを渡すときに使います。
code:ts
const { data } = useSuspenseQuery(MY_QUERY, {
context: {
headers: { authorization: "Bearer token" },
},
});
5. client
型: ApolloClient
説明:
デフォルトの Apollo Client ではなく、特定の Client インスタンスを明示的に使用したいとき。
code:ts
const { data } = useSuspenseQuery(MY_QUERY, {
client: customApolloClient,
});
6. queryKey
型: string | number | any[]
説明:
Suspense のキャッシュキーを安定化させるためのユニーク識別子。
同じクエリを複数コンポーネントで使う場合や、再フェッチのトリガーに利用します。
code:ts
const { data } = useSuspenseQuery(MY_QUERY, {
queryKey: "user", userId,
});
skipToken (apollo)