apollo-client-patterns
Use when implementing Apollo Client patterns for queries, mutations, cache management, and local state in React applications.
What this skill does
# Apollo Client Patterns
Master Apollo Client for building efficient GraphQL applications with proper
query management, caching strategies, and state handling.
## Overview
Apollo Client is a comprehensive state management library for JavaScript that
enables you to manage both local and remote data with GraphQL. It integrates
seamlessly with React and provides powerful caching mechanisms.
## Installation and Setup
### Installing Apollo Client
```bash
# Install Apollo Client and dependencies
npm install @apollo/client graphql
# For React applications
npm install @apollo/client graphql react
# Additional packages
npm install graphql-tag @apollo/client/link/error
```
### Basic Configuration
```javascript
// src/apollo/client.js
import {
ApolloClient,
InMemoryCache,
createHttpLink,
from
} from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
const httpLink = createHttpLink({
uri: process.env.REACT_APP_GRAPHQL_URI || 'http://localhost:4000/graphql',
});
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('authToken');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
}
};
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path }) =>
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
}
if (networkError) {
console.error(`[Network error]: ${networkError}`);
}
});
const client = new ApolloClient({
link: from([errorLink, authLink, httpLink]),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
posts: {
merge(existing, incoming) {
return incoming;
}
}
}
}
}
}),
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'all',
},
query: {
fetchPolicy: 'network-only',
errorPolicy: 'all',
},
},
});
export default client;
```
### Provider Setup
```javascript
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider } from '@apollo/client';
import client from './apollo/client';
import App from './App';
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root')
);
```
## Core Patterns
### 1. Basic Queries
```javascript
// src/graphql/queries.js
import { gql } from '@apollo/client';
export const GET_POSTS = gql`
query GetPosts($limit: Int, $offset: Int) {
posts(limit: $limit, offset: $offset) {
id
title
body
author {
id
name
avatar
}
createdAt
}
}
`;
export const GET_POST = gql`
query GetPost($id: ID!) {
post(id: $id) {
id
title
body
author {
id
name
}
comments {
id
body
author {
id
name
}
}
}
}
`;
// src/components/PostsList.js
import React from 'react';
import { useQuery } from '@apollo/client';
import { GET_POSTS } from '../graphql/queries';
function PostsList() {
const { loading, error, data, refetch, fetchMore } = useQuery(GET_POSTS, {
variables: { limit: 10, offset: 0 },
notifyOnNetworkStatusChange: true,
});
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<button onClick={() => refetch()}>Refresh</button>
{data.posts.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
<span>By {post.author.name}</span>
</article>
))}
<button
onClick={() =>
fetchMore({
variables: { offset: data.posts.length },
updateQuery: (prev, { fetchMoreResult }) => {
if (!fetchMoreResult) return prev;
return {
posts: [...prev.posts, ...fetchMoreResult.posts]
};
}
})
}
>
Load More
</button>
</div>
);
}
export default PostsList;
```
### 2. Mutations
```javascript
// src/graphql/mutations.js
import { gql } from '@apollo/client';
export const CREATE_POST = gql`
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
title
body
author {
id
name
}
createdAt
}
}
`;
export const UPDATE_POST = gql`
mutation UpdatePost($id: ID!, $input: UpdatePostInput!) {
updatePost(id: $id, input: $input) {
id
title
body
}
}
`;
export const DELETE_POST = gql`
mutation DeletePost($id: ID!) {
deletePost(id: $id) {
id
}
}
`;
// src/components/CreatePost.js
import React, { useState } from 'react';
import { useMutation } from '@apollo/client';
import { CREATE_POST } from '../graphql/mutations';
import { GET_POSTS } from '../graphql/queries';
function CreatePost() {
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [createPost, { loading, error }] = useMutation(CREATE_POST, {
update(cache, { data: { createPost } }) {
const { posts } = cache.readQuery({ query: GET_POSTS });
cache.writeQuery({
query: GET_POSTS,
data: { posts: [createPost, ...posts] }
});
},
onCompleted: () => {
setTitle('');
setBody('');
},
onError: (error) => {
console.error('Error creating post:', error);
}
});
const handleSubmit = (e) => {
e.preventDefault();
createPost({
variables: {
input: { title, body }
}
});
};
return (
<form onSubmit={handleSubmit}>
<input
value={title}
onChange={e => setTitle(e.target.value)}
placeholder="Title"
disabled={loading}
/>
<textarea
value={body}
onChange={e => setBody(e.target.value)}
placeholder="Body"
disabled={loading}
/>
<button type="submit" disabled={loading}>
{loading ? 'Creating...' : 'Create Post'}
</button>
{error && <p>Error: {error.message}</p>}
</form>
);
}
export default CreatePost;
```
### 3. Cache Management
```javascript
// src/apollo/cache.js
import { InMemoryCache, makeVar } from '@apollo/client';
// Reactive variables
export const cartItemsVar = makeVar([]);
export const isLoggedInVar = makeVar(!!localStorage.getItem('authToken'));
export const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
cartItems: {
read() {
return cartItemsVar();
}
},
isLoggedIn: {
read() {
return isLoggedInVar();
}
},
// Pagination with field policies
posts: {
keyArgs: false,
merge(existing = [], incoming, { args }) {
const merged = existing ? existing.slice(0) : [];
const offset = args?.offset || 0;
for (let i = 0; i < incoming.length; i++) {
merged[offset + i] = incoming[i];
}
return merged;
}
}
}
},
Post: {
fields: {
// Computed field
isLiked: {
read(_, { readField }) {
const likes = readField('likes');
const currentUserId = localStorage.getItem('userId');
return likes?.some(like => like.userId === currentUserId);
}
}
}
}
}
});
// Cache manipulation helpers
export function addToCart(item) {
const currentCart = cartItemsVar();
cartItemsVar([...currentCart, item]);
}
export function removeFromCart(itemId) {
const currentCart = cartItemsVar();
cartItemsVar(currentCart.filter(itRelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.