跳到正文
cccskills
免费在 GitHub 公开

apollo-client

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.

中文简介正在准备中。当前显示原文说明。

查看安装方法

包含的文件(2)

  • SKILL.md5.1 KB
  • _scores.json1.2 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

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

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Scripts and configures production rendering in Autodesk 3ds Max with the V-Ray and Corona renderers: output size and files, render elements, denoising, light mix, batch and command-line rendering, and network rendering. Use when a user asks to set up a production render, render several cameras in one batch, render from the command line or on a render farm, add render passes for compositing, or cut render time for archviz and product shots.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

Covers scripting Autodesk 3ds Max, the 3D modeling and rendering application, with MAXScript and Python (pymxs): scene manipulation, object creation, material assignment, camera and light setup, batch operations, and file I/O. Use when tasks involve automating repetitive 3ds Max workflows, batch processing scenes, running scripts headless with 3dsmaxbatch, creating custom tools, or scripting scene setup for archviz, product visualization, or VFX.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

3proxy

免费

3proxy is a small open-source proxy server that runs HTTP/HTTPS, SOCKS4/5, SNI and TCP/UDP port-mapping proxies from one config file. Use when a user asks to set up an HTTP or SOCKS5 proxy, add proxy users and passwords, write 3proxy access rules, chain or rotate upstream (parent) proxies, limit bandwidth, connections or monthly traffic per user, run 3proxy in Docker, or fix a 3proxy.cfg that will not start.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

Builds Agent2Agent (A2A) servers and clients, the open protocol (originally from Google, now under the Linux Foundation) that lets AI agents from different frameworks call each other. Use when the user wants to create an A2A-compliant agent, build an Agent Card, implement task management, connect agents across frameworks, set up agent discovery, handle streaming responses, implement push notifications, or orchestrate multi-agent workflows. Trigger words: a2a, agent to agent, agent2agent, a2a protocol, a2a server, a2a client, agent card, agent interoperability, agent collaboration, multi-agent, agent discovery, a2a sdk, a2a task.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

Plans a controlled experiment (A/B test) so its result can be trusted: writes the hypothesis, picks one primary metric and the guardrails, computes sample size and run time, specifies how visitors are assigned and when exposure is logged, and reads out the result with a confidence interval. Use when someone says "set up an A/B test", "split test this page", "how many visitors do I need", "how long should the experiment run", "is this result significant", "can I stop the test early", or wants to test a headline, price, layout or onboarding change against the current version.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

ably

免费

Ably is a hosted realtime messaging service: clients publish and subscribe to named channels over WebSockets, see who is present, replay message history, and resume after a dropped connection. Use when a user asks to "add realtime updates", "push live notifications to the browser", "show who is online", "add a chat room with typing indicators", "publish from a serverless function", or "authenticate Ably clients without exposing the API key". Covers the ably 2.x JavaScript SDK (Realtime and REST), JWT token authentication, presence, history and rewind, batch publishing, and the @ably/chat 1.x SDK.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

查看 TerminalSkills 的全部技能

报告此技能的问题