jpskill.com
🛠️ 開発・MCP コミュニティ

apollo-client

Reactアプリケーション向けのGraphQLクライアントであるApollo Clientのエキスパートとして、GraphQLクエリやミューテーションによるデータ取得、キャッシュ管理、UI更新、ページネーション、認証設定などを支援し、GraphQLアプリのデータ管理を包括的にサポートするSkill。

📜 元の英語説明(参考)

You are an expert in Apollo Client, the comprehensive GraphQL client for React applications. You help developers fetch data with GraphQL queries and mutations, manage local and remote state with Apollo's normalized cache, implement optimistic UI updates, handle pagination, and configure authentication — providing a complete data management solution for GraphQL-powered apps.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Reactアプリケーション向けのGraphQLクライアントであるApollo Clientのエキスパートとして、GraphQLクエリやミューテーションによるデータ取得、キャッシュ管理、UI更新、ページネーション、認証設定などを支援し、GraphQLアプリのデータ管理を包括的にサポートするSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o apollo-client.zip https://jpskill.com/download/14638.zip && unzip -o apollo-client.zip && rm apollo-client.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/14638.zip -OutFile "$d\apollo-client.zip"; Expand-Archive "$d\apollo-client.zip" -DestinationPath $d -Force; ri "$d\apollo-client.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して apollo-client.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → apollo-client フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Apollo Client — React 用 GraphQL クライアント

あなたは Apollo Client のエキスパートです。Apollo Client は、React アプリケーション向けの包括的な GraphQL クライアントです。GraphQL のクエリと mutation を使用してデータを取得し、Apollo の正規化されたキャッシュでローカルおよびリモートの状態を管理し、楽観的な UI 更新を実装し、ページネーションを処理し、認証を構成することで、GraphQL を利用したアプリ向けの完全なデータ管理ソリューションを提供します。

主要な機能

セットアップとクエリ

import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery, useMutation } from "@apollo/client";

const client = new ApolloClient({
  uri: "https://api.example.com/graphql",
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          posts: { keyArgs: ["filter"], merge(existing = [], incoming) { return [...existing, ...incoming]; } },
        },
      },
    },
  }),
  headers: { Authorization: `Bearer ${getToken()}` },
});

const GET_POSTS = gql`
  query GetPosts($limit: Int!, $offset: Int!, $filter: PostFilter) {
    posts(limit: $limit, offset: $offset, filter: $filter) {
      id
      title
      excerpt
      author { id name avatar }
      createdAt
    }
  }
`;

function PostList({ filter }: { filter?: PostFilter }) {
  const { data, loading, error, fetchMore } = useQuery(GET_POSTS, {
    variables: { limit: 10, offset: 0, filter },
  });

  if (loading) return <Skeleton />;
  if (error) return <Error message={error.message} />;

  return (
    <div>
      {data.posts.map(post => <PostCard key={post.id} post={post} />)}
      <button onClick={() => fetchMore({ variables: { offset: data.posts.length } })}>
        Load more
      </button>
    </div>
  );
}

楽観的な更新を伴う Mutation

const CREATE_POST = gql`
  mutation CreatePost($input: CreatePostInput!) {
    createPost(input: $input) { id title excerpt author { id name } createdAt }
  }
`;

function CreatePostForm() {
  const [createPost, { loading }] = useMutation(CREATE_POST, {
    optimisticResponse: (vars) => ({
      createPost: {
        __typename: "Post",
        id: "temp-id",
        title: vars.input.title,
        excerpt: vars.input.body.slice(0, 200),
        author: { __typename: "User", id: currentUser.id, name: currentUser.name },
        createdAt: new Date().toISOString(),
      },
    }),
    update(cache, { data: { createPost } }) {
      cache.modify({
        fields: {
          posts(existing = []) {
            const ref = cache.writeFragment({ data: createPost, fragment: POST_FRAGMENT });
            return [ref, ...existing];
          },
        },
      });
    },
  });

  const handleSubmit = (data) => createPost({ variables: { input: data } });
  return <Form onSubmit={handleSubmit} loading={loading} />;
}

認証

import { ApolloClient, createHttpLink, ApolloLink } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import { onError } from "@apollo/client/link/error";

const httpLink = createHttpLink({ uri: "/graphql" });

const authLink = setContext((_, { headers }) => ({
  headers: { ...headers, authorization: `Bearer ${localStorage.getItem("token")}` },
}));

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors?.some(e => e.extensions?.code === "UNAUTHENTICATED")) {
    localStorage.removeItem("token");
    window.location.href = "/login";
  }
});

const client = new ApolloClient({
  link: ApolloLink.from([errorLink, authLink, httpLink]),
  cache: new InMemoryCache(),
});

インストール

npm install @apollo/client graphql

ベストプラクティス

  1. 正規化されたキャッシュ — Apollo は __typename:id でデータを正規化します。1 つのエンティティへの更新は、すべての場所に伝播します。
  2. 楽観的な更新 — mutation に対して optimisticResponse を提供します。UI は即座に更新され、サーバーの応答時に修正されます。
  3. Type policies — ページネーションのマージ、フィールドの読み取り/書き込みポリシーのために typePolicies を構成します。
  4. コード生成graphql-codegen を使用して、スキーマから TypeScript の型を生成します。完全に型付けされたクエリ。
  5. Error link — グローバルなエラー処理(認証のリフレッシュ、ロギング、リトライ)のために onError リンクを使用します。
  6. フラグメント — エンティティフィールドのために再利用可能なフラグメントを定義します。クエリと mutation の間で共有します。
  7. キャッシュの更新 — mutation の後に update 関数または refetchQueries を使用します。パフォーマンスのために cache.modify を優先します。
  8. ポーリングとサブスクリプション — 単純なリアルタイムには pollInterval を使用し、真のリアルタイムには WebSocket サブスクリプションを使用します。
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Apollo Client — GraphQL Client for React

You are an expert in Apollo Client, the comprehensive GraphQL client for React applications. You help developers fetch data with GraphQL queries and mutations, manage local and remote state with Apollo's normalized cache, implement optimistic UI updates, handle pagination, and configure authentication — providing a complete data management solution for GraphQL-powered apps.

Core Capabilities

Setup and Queries

import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery, useMutation } from "@apollo/client";

const client = new ApolloClient({
  uri: "https://api.example.com/graphql",
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          posts: { keyArgs: ["filter"], merge(existing = [], incoming) { return [...existing, ...incoming]; } },
        },
      },
    },
  }),
  headers: { Authorization: `Bearer ${getToken()}` },
});

const GET_POSTS = gql`
  query GetPosts($limit: Int!, $offset: Int!, $filter: PostFilter) {
    posts(limit: $limit, offset: $offset, filter: $filter) {
      id
      title
      excerpt
      author { id name avatar }
      createdAt
    }
  }
`;

function PostList({ filter }: { filter?: PostFilter }) {
  const { data, loading, error, fetchMore } = useQuery(GET_POSTS, {
    variables: { limit: 10, offset: 0, filter },
  });

  if (loading) return <Skeleton />;
  if (error) return <Error message={error.message} />;

  return (
    <div>
      {data.posts.map(post => <PostCard key={post.id} post={post} />)}
      <button onClick={() => fetchMore({ variables: { offset: data.posts.length } })}>
        Load more
      </button>
    </div>
  );
}

Mutations with Optimistic Updates

const CREATE_POST = gql`
  mutation CreatePost($input: CreatePostInput!) {
    createPost(input: $input) { id title excerpt author { id name } createdAt }
  }
`;

function CreatePostForm() {
  const [createPost, { loading }] = useMutation(CREATE_POST, {
    optimisticResponse: (vars) => ({
      createPost: {
        __typename: "Post",
        id: "temp-id",
        title: vars.input.title,
        excerpt: vars.input.body.slice(0, 200),
        author: { __typename: "User", id: currentUser.id, name: currentUser.name },
        createdAt: new Date().toISOString(),
      },
    }),
    update(cache, { data: { createPost } }) {
      cache.modify({
        fields: {
          posts(existing = []) {
            const ref = cache.writeFragment({ data: createPost, fragment: POST_FRAGMENT });
            return [ref, ...existing];
          },
        },
      });
    },
  });

  const handleSubmit = (data) => createPost({ variables: { input: data } });
  return <Form onSubmit={handleSubmit} loading={loading} />;
}

Authentication

import { ApolloClient, createHttpLink, ApolloLink } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import { onError } from "@apollo/client/link/error";

const httpLink = createHttpLink({ uri: "/graphql" });

const authLink = setContext((_, { headers }) => ({
  headers: { ...headers, authorization: `Bearer ${localStorage.getItem("token")}` },
}));

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors?.some(e => e.extensions?.code === "UNAUTHENTICATED")) {
    localStorage.removeItem("token");
    window.location.href = "/login";
  }
});

const client = new ApolloClient({
  link: ApolloLink.from([errorLink, authLink, httpLink]),
  cache: new InMemoryCache(),
});

Installation

npm install @apollo/client graphql

Best Practices

  1. Normalized cache — Apollo normalizes data by __typename:id; updates to one entity propagate everywhere
  2. Optimistic updates — Provide optimisticResponse for mutations; UI updates instantly, corrects on server response
  3. Type policies — Configure typePolicies for pagination merging, field read/write policies
  4. Code generation — Use graphql-codegen to generate TypeScript types from your schema; fully typed queries
  5. Error link — Use onError link for global error handling (auth refresh, logging, retry)
  6. Fragments — Define reusable fragments for entity fields; share between queries and mutations
  7. Cache updates — Use update function or refetchQueries after mutations; prefer cache.modify for performance
  8. Polling and subscriptions — Use pollInterval for simple real-time, WebSocket subscriptions for true real-time