JavaScript and React course ยท Module 10: React Ecosystem and Future

Apollo Client - Comprehensive GraphQL Integration with React

16 min read ยท
In this lesson6

The command center asks a GraphQL server for users, their posts and comments. If every component called fetch on its own, the same data would arrive many times, and after a post is edited some screens would show the old version. Apollo Client sends GraphQL queries, keeps the responses in a normalized cache and refreshes components when the data changes. It also handles optimistic updates and subscriptions.

Installation and Basic Configuration

Apollo Client 4 needs three packages: @apollo/client, graphql and rxjs, because version 4 is built on RxJS observables:

npm install @apollo/client graphql rxjs
# Optional: WebSocket subscriptions and file uploads
npm install graphql-ws apollo-upload-client

The examples in this lesson use the Apollo Client 4 API: you import the client, the cache and the links from @apollo/client, and ApolloProvider and hooks such as useQuery from @apollo/client/react. In older projects you will meet the version 3 API, where hooks were imported straight from @apollo/client and the client accepted a uri option.

The client is a chain of links that every query passes through, plus a cache:

// apolloClient.js
import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, CombinedGraphQLErrors, ServerError } from '@apollo/client';
import { SetContextLink } from '@apollo/client/link/context';
import { ErrorLink } from '@apollo/client/link/error';

// HTTP link for GraphQL server communication
const httpLink = new HttpLink({
  uri: process.env.REACT_APP_GRAPHQL_ENDPOINT || 'http://localhost:4000/graphql',
  credentials: 'include' // For cookies/session
});

// Link for authorization handling
const authLink = new SetContextLink(({ headers }) => {
  const token = localStorage.getItem('authToken');

  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
      'x-api-version': '1.0',
      'x-client-name': 'react-app'
    }
  };
});

// Link for error handling
const errorLink = new ErrorLink(({ error, operation, forward }) => {
  if (CombinedGraphQLErrors.is(error)) {
    error.errors.forEach(({ message, locations, path, extensions }) => {
      console.error(
        `GraphQL error: Message: ${message}, Location: ${JSON.stringify(locations)}, Path: ${path}`
      );

      // Handle specific errors
      if (extensions?.code === 'UNAUTHENTICATED') {
        localStorage.removeItem('authToken');
        window.location.href = '/login';
      }
    });
  } else if (ServerError.is(error)) {
    console.error(`Server error: ${error.statusCode}`);

    // Retry the request after a server error
    if (error.statusCode === 500) {
      return forward(operation);
    }
  } else {
    console.error(`Network error: ${error}`);
  }
});

// Cache configuration
const cache = new InMemoryCache({
  typePolicies: {
    User: {
      fields: {
        // Cache configuration for user fields
        posts: {
          merge(existing = [], incoming) {
            return [...existing, ...incoming];
          }
        }
      }
    },
    Post: {
      fields: {
        comments: {
          merge(existing = [], incoming) {
            return incoming;
          }
        }
      }
    }
  }
});

// Main Apollo client
const apolloClient = new ApolloClient({
  link: ApolloLink.from([errorLink, authLink, httpLink]),
  cache,
  defaultOptions: {
    watchQuery: {
      errorPolicy: 'all',
      notifyOnNetworkStatusChange: true
    },
    query: {
      errorPolicy: 'all'
    }
  },
  devtools: { enabled: process.env.NODE_ENV === 'development' }
});

export default apolloClient;

ApolloLink.from([errorLink, authLink, httpLink]) sets the order: error handling, authorization header, HTTP dispatch. ErrorLink receives a single error object: CombinedGraphQLErrors.is(error) recognizes errors returned by GraphQL, and ServerError.is(error) an HTTP response with an error status. In SetContextLink the first argument is the previous context, hence ({ headers }). InMemoryCache normalizes the responses, meaning it stores each object separately under a key made of __typename and id, so a repeated query for the same data does not reach the server. typePolicies decide how lists are merged.

You make the client available to the whole application through ApolloProvider, much like context:

// App.js
import React from 'react';
import { ApolloProvider } from '@apollo/client/react';
import apolloClient from './apolloClient';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Dashboard from './components/Dashboard';
import UserProfile from './components/UserProfile';

function App() {
  return (
    <ApolloProvider client={apolloClient}>
      <Router>
        <div className="App">
          <Routes>
            <Route path="/" element={<Dashboard />} />
            <Route path="/profile/:id" element={<UserProfile />} />
          </Routes>
        </div>
      </Router>
    </ApolloProvider>
  );
}

export default App;

Every component inside the provider now uses the Apollo hooks and the shared cache.

Running Queries

useQuery runs a query automatically on render and returns data, loading and error. You describe the query with the gql template and pass the variables in the variables option:

// GraphQL query definition
import { gql } from '@apollo/client';
import { useQuery } from '@apollo/client/react';

const GET_USERS = gql`
  query GetUsers($limit: Int, $offset: Int) {
    users(limit: $limit, offset: $offset) {
      id
      name
      email
      avatar
      posts {
        id
        title
        createdAt
      }
    }
  }
`;

function UsersList() {
  const { data, loading, error, refetch, fetchMore } = useQuery(GET_USERS, {
    variables: { limit: 10, offset: 0 },
    notifyOnNetworkStatusChange: true,
    errorPolicy: 'all'
  });

  if (loading) return <div className="loading">Loading users...</div>;
  if (error) return <div className="error">Error: {error.message}</div>;

  const loadMoreUsers = () => {
    fetchMore({
      variables: {
        offset: data.users.length
      },
      updateQuery: (prev, { fetchMoreResult }) => {
        if (!fetchMoreResult) return prev;

        return {
          ...prev,
          users: [...prev.users, ...fetchMoreResult.users]
        };
      }
    });
  };

  return (
    <div>
      <h2>Users List</h2>
      <button onClick={() => refetch()}>Refresh</button>

      <div className="users-grid">
        {data.users.map(user => (
          <div key={user.id} className="user-card">
            <img src={user.avatar} alt={user.name} />
            <h3>{user.name}</h3>
            <p>{user.email}</p>
            <p>Posts: {user.posts.length}</p>
          </div>
        ))}
      </div>

      <button onClick={loadMoreUsers}>Load More</button>
    </div>
  );
}

The order matters: first you check loading, then error, and only at the end do you render data. fetchMore pulls in the next page, and updateQuery appends the new users to the previous ones.

On-Demand Queries

A search box should ask the server only after a click. useLazyQuery returns a function that runs the query on demand:

import { gql } from '@apollo/client';
import { useLazyQuery } from '@apollo/client/react';
import { useState } from 'react';

const SEARCH_USERS = gql`
  query SearchUsers($query: String!) {
    searchUsers(query: $query) {
      id
      name
      email
      avatar
    }
  }
`;

function UserSearch() {
  const [searchTerm, setSearchTerm] = useState('');
  const [searchUsers, { data, loading, error }] = useLazyQuery(SEARCH_USERS);

  const handleSearch = (e) => {
    e.preventDefault();
    if (searchTerm.trim()) {
      searchUsers({
        variables: { query: searchTerm }
      });
    }
  };

  return (
    <div>
      <form onSubmit={handleSearch}>
        <input
          type="text"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          />
        <button type="submit">Search</button>
      </form>

      {loading && <div>Searching...</div>}
      {error && <div>Search error: {error.message}</div>}

      {data?.searchUsers && (
        <div>
          <h3>Search Results:</h3>
          {data.searchUsers.map(user => (
            <div key={user.id}>{user.name} - {user.email}</div>
          ))}
        </div>
      )}
    </div>
  );
}

You call searchUsers in handleSearch, and the loading and error states work just like in useQuery.

Mutations

A mutation changes data on the server. Unlike useQuery, the useMutation hook sends nothing by itself, it only returns a function that you call on demand, e.g. in onSubmit:

import { gql } from '@apollo/client';
import { useMutation } from '@apollo/client/react';
import { useState } from 'react';

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

const GET_POSTS = gql`
  query GetPosts {
    posts {
      id
      title
      content
      author {
        id
        name
      }
      createdAt
    }
  }
`;

function CreatePostForm() {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');

  const [createPost, { loading, error }] = useMutation(CREATE_POST, {
    // Update cache after creating a post
    update(cache, { data: { createPost } }) {
      const existingPosts = cache.readQuery({ query: GET_POSTS });

      cache.writeQuery({
        query: GET_POSTS,
        data: {
          posts: [createPost, ...existingPosts.posts]
        }
      });
    },

    // Optimistic update
    optimisticResponse: {
      createPost: {
        __typename: 'Post',
        id: 'temp-id',
        title,
        content,
        author: {
          __typename: 'User',
          id: 'current-user-id',
          name: 'You'
        },
        createdAt: new Date().toISOString()
      }
    },

    // Error handling
    onError: (error) => {
      console.error('Error creating post:', error);
    },

    onCompleted: (data) => {
      console.log('Post created:', data.createPost);
      setTitle('');
      setContent('');
    }
  });

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!title.trim() || !content.trim()) {
      alert('Please fill in all fields');
      return;
    }

    try {
      await createPost({
        variables: {
          input: { title, content }
        }
      });
    } catch (err) {
      console.error('Error creating post:', err);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Title:</label>
        <input
          type="text"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          disabled={loading}
        />
      </div>

      <div>
        <label>Content:</label>
        <textarea
          value={content}
          onChange={(e) => setContent(e.target.value)}
          disabled={loading}
        />
      </div>

      <button type="submit" disabled={loading}>
        {loading ? 'Creating...' : 'Create Post'}
      </button>

      {error && <div className="error">Error: {error.message}</div>}
    </form>
  );
}

update writes the new post into the GET_POSTS query in the cache, so the list refreshes without asking the server. optimisticResponse shows the post immediately, and if the mutation fails, Apollo rolls back this temporary version.

Advanced Cache Management

When a post is deleted, the cache has to be cleaned up by hand, because Apollo does not know which lists contained that object:

import { gql } from '@apollo/client';
import { useMutation, useQuery } from '@apollo/client/react';

const DELETE_POST = gql`
  mutation DeletePost($id: ID!) {
    deletePost(id: $id) {
      id
    }
  }
`;

const UPDATE_POST = gql`
  mutation UpdatePost($id: ID!, $input: UpdatePostInput!) {
    updatePost(id: $id, input: $input) {
      id
      title
      content
      updatedAt
    }
  }
`;

function PostManager({ postId }) {
  const [deletePost] = useMutation(DELETE_POST, {
    // Remove from cache after deletion
    update(cache, { data: { deletePost } }) {
      cache.modify({
        fields: {
          posts(existingPosts = [], { readField }) {
            return existingPosts.filter(
              postRef => deletePost.id !== readField('id', postRef)
            );
          }
        }
      });

      // Also remove the individual post from cache
      cache.evict({ id: cache.identify({ __typename: 'Post', id: deletePost.id }) });
      cache.gc();
    }
  });

  const [updatePost] = useMutation(UPDATE_POST, {
    // No update needed - Apollo automatically updates cache
    // if returned data has the same ID and __typename
  });

  const handleDelete = async () => {
    if (window.confirm('Are you sure you want to delete this post?')) {
      try {
        await deletePost({
          variables: { id: postId }
        });
      } catch (error) {
        console.error('Error deleting post:', error);
      }
    }
  };

  const handleUpdate = async (newTitle, newContent) => {
    try {
      await updatePost({
        variables: {
          id: postId,
          input: { title: newTitle, content: newContent }
        }
      });
    } catch (error) {
      console.error('Error updating post:', error);
    }
  };

  return (
    <div>
      <button onClick={handleDelete}>Delete Post</button>
      {/* Edit form */}
    </div>
  );
}

cache.modify cuts the reference out of the posts list, and evict and gc remove the object itself. For an update you do not have to do anything: a response with the same id and __typename overwrites the object in the cache by itself.

Subscriptions

Subscriptions deliver data in real time over WebSocket. ApolloLink.split routes them to GraphQLWsLink, and queries and mutations to HTTP:

// apolloClient.js - extended configuration
import { OperationTypeNode } from 'graphql';
import { ApolloLink } from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';

// WebSocket link for subscriptions
const wsLink = new GraphQLWsLink(
  createClient({
    url: process.env.REACT_APP_GRAPHQL_WS_ENDPOINT || 'ws://localhost:4000/graphql',
    connectionParams: () => {
      const token = localStorage.getItem('authToken');
      return {
        authorization: token ? `Bearer ${token}` : ''
      };
    },
    on: {
      connected: () => console.log('WebSocket connected'),
      closed: () => console.log('WebSocket disconnected')
    }
  })
);

// Traffic splitting - HTTP for queries/mutations, WebSocket for subscriptions
const splitLink = ApolloLink.split(
  ({ operationType }) => operationType === OperationTypeNode.SUBSCRIPTION,
  wsLink,
  ApolloLink.from([errorLink, authLink, httpLink])
);

// Updated client
const apolloClient = new ApolloClient({
  link: splitLink, // Use splitLink instead of ApolloLink.from([...])
  cache,
  // ... rest of configuration
});

In version 4 the operation has an operationType field, so the test compares it with OperationTypeNode.SUBSCRIPTION from the graphql package. The graphql-ws package is the successor of the unmaintained subscriptions-transport-ws, so choose it.

A component listens for events with the useSubscription hook and adds new posts to the cache:

import { gql } from '@apollo/client';
import { useSubscription, useQuery } from '@apollo/client/react';

const POST_ADDED_SUBSCRIPTION = gql`
  subscription PostAdded {
    postAdded {
      id
      title
      content
      author {
        id
        name
      }
      createdAt
    }
  }
`;

const COMMENT_ADDED_SUBSCRIPTION = gql`
  subscription CommentAdded($postId: ID!) {
    commentAdded(postId: $postId) {
      id
      content
      author {
        id
        name
      }
      createdAt
    }
  }
`;

function LivePostsFeed() {
  const { data: postsData, loading } = useQuery(GET_POSTS);

  // Subscribe to new posts
  useSubscription(POST_ADDED_SUBSCRIPTION, {
    onData: ({ data, client }) => {
      const newPost = data.data.postAdded;

      // Update cache
      const existingPosts = client.readQuery({ query: GET_POSTS });
      client.writeQuery({
        query: GET_POSTS,
        data: {
          posts: [newPost, ...existingPosts.posts]
        }
      });

      // Show notification
      showNotification(`New post: ${newPost.title}`);
    }
  });

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      <h2>Live Posts</h2>
      {postsData?.posts.map(post => (
        <LivePostCard key={post.id} post={post} />
      ))}
    </div>
  );
}

function LivePostCard({ post }) {
  // Subscribe to new comments for this post
  useSubscription(COMMENT_ADDED_SUBSCRIPTION, {
    variables: { postId: post.id },
    onData: ({ data }) => {
      const newComment = data.data.commentAdded;
      console.log(`New comment on post ${post.title}:`, newComment.content);
    }
  });

  return (
    <div className="post-card">
      <h3>{post.title}</h3>
      <p>{post.content}</p>
      <small>Author: {post.author.name}</small>
    </div>
  );
}

onData receives the client and the subscription result, so the new post is in data.data.postAdded. Apollo Client 4 removed the older onSubscriptionData name, so such a callback no longer fires.

Advanced Patterns

A fragment is a reusable set of fields. You define USER_FRAGMENT once and paste it into every query about a user:

// fragments.js
import { gql } from '@apollo/client';

export const USER_FRAGMENT = gql`
  fragment UserInfo on User {
    id
    name
    email
    avatar
  }
`;

export const POST_FRAGMENT = gql`
  fragment PostInfo on Post {
    id
    title
    content
    createdAt
    author {
      ...UserInfo
    }
  }
  ${USER_FRAGMENT}
`;

// Using fragments
const GET_POSTS_WITH_FRAGMENTS = gql`
  query GetPosts {
    posts {
      ...PostInfo
    }
  }
  ${POST_FRAGMENT}
`;

Changing the fields in the fragment updates every query that uses it, and ${USER_FRAGMENT} attaches its definition to the document.

usePostOperations wraps a query, a mutation and pagination in one hook, so the page component sees a simple API:

// hooks/usePostOperations.js
import { gql } from '@apollo/client';
import { useQuery, useMutation } from '@apollo/client/react';
import { POST_FRAGMENT } from '../fragments';

const GET_POSTS = gql`
  query GetPosts($limit: Int, $offset: Int) {
    posts(limit: $limit, offset: $offset) {
      ...PostInfo
    }
  }
  ${POST_FRAGMENT}
`;

const CREATE_POST = gql`
  mutation CreatePost($input: CreatePostInput!) {
    createPost(input: $input) {
      ...PostInfo
    }
  }
  ${POST_FRAGMENT}
`;

export function usePostOperations() {
  const { data, loading, error, refetch, fetchMore } = useQuery(GET_POSTS, {
    variables: { limit: 10, offset: 0 }
  });

  const [createPostMutation, { loading: creating }] = useMutation(CREATE_POST, {
    update(cache, { data: { createPost } }) {
      const existingPosts = cache.readQuery({ query: GET_POSTS });
      cache.writeQuery({
        query: GET_POSTS,
        data: {
          posts: [createPost, ...existingPosts.posts]
        }
      });
    }
  });

  const createPost = async (postData) => {
    try {
      const result = await createPostMutation({
        variables: { input: postData }
      });
      return { success: true, post: result.data.createPost };
    } catch (error) {
      return { success: false, error: error.message };
    }
  };

  const loadMore = () => {
    return fetchMore({
      variables: { offset: data?.posts?.length || 0 },
      updateQuery: (prev, { fetchMoreResult }) => ({
        ...prev,
        posts: [...prev.posts, ...fetchMoreResult.posts]
      })
    });
  };

  return {
    posts: data?.posts || [],
    loading,
    error,
    creating,
    createPost,
    refetch,
    loadMore
  };
}

// Using the custom hook
function PostsPage() {
  const { posts, loading, createPost, loadMore } = usePostOperations();

  const handleCreatePost = async (formData) => {
    const result = await createPost(formData);
    if (result.success) {
      console.log('Post created successfully');
    } else {
      console.error('Failed to create post:', result.error);
    }
  };

  return (
    <div>
      <CreatePostForm onSubmit={handleCreatePost} />
      {loading ? (
        <div>Loading...</div>
      ) : (
        <PostsList posts={posts} onLoadMore={loadMore} />
      )}
    </div>
  );
}

PostsPage knows nothing about GraphQL. When you change the schema, you fix one hook instead of ten components, and I recommend this split.

GraphQLErrorBoundary catches a rendering error and shows a fallback screen with a retry button, instead of bringing down the whole tree:

import React from 'react';
import { CombinedGraphQLErrors, ServerError } from '@apollo/client';
import { ApolloProvider } from '@apollo/client/react';

class GraphQLErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    if (CombinedGraphQLErrors.is(error)) {
      console.error('GraphQL Error:', error.errors);
    } else if (ServerError.is(error)) {
      console.error('Server Error:', error.statusCode);
    }

    // Send error to monitoring system
    this.logErrorToService(error, errorInfo);
  }

  logErrorToService(error, errorInfo) {
    // Integration with Sentry, LogRocket, etc.
    console.error('Error logged:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-boundary">
          <h2>Something went wrong with GraphQL</h2>
          <details>
            <summary>Error details</summary>
            <pre>{this.state.error?.message}</pre>
          </details>
          <button onClick={() => this.setState({ hasError: false, error: null })}>
            Try again
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

// Usage
function App() {
  return (
    <ApolloProvider client={apolloClient}>
      <GraphQLErrorBoundary>
        <Router>
          {/* Your application */}
        </Router>
      </GraphQLErrorBoundary>
    </ApolloProvider>
  );
}

Apollo Client 4 no longer has the ApolloError class from version 3: you recognize GraphQL errors with CombinedGraphQLErrors.is(error) (the list is in error.errors), and an HTTP response with an error status with ServerError.is(error). They reach an error boundary from hooks such as useSuspenseQuery, because useQuery does not throw the error, it returns it in the error field.

For tests there is MockedProvider, which returns prepared responses instead of a server:

// __tests__/UsersList.test.js
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/client/testing/react';
import UsersList, { GET_USERS } from '../UsersList';

const mocks = [
  {
    request: {
      query: GET_USERS,
      variables: { limit: 10, offset: 0 }
    },
    result: {
      data: {
        users: [
          {
            __typename: 'User',
            id: '1',
            name: 'John Doe',
            email: 'john@example.com',
            avatar: 'https://example.com/avatar1.jpg',
            posts: []
          }
        ]
      }
    }
  }
];

test('renders users list', async () => {
  render(
    <MockedProvider mocks={mocks}>
      <UsersList />
    </MockedProvider>
  );

  // Check loading state
  expect(screen.getByText('Loading users...')).toBeInTheDocument();

  // Wait for data to load
  await waitFor(() => {
    expect(screen.getByText('John Doe')).toBeInTheDocument();
  });
});

test('handles error state', async () => {
  const errorMocks = [
    {
      request: {
        query: GET_USERS,
        variables: { limit: 10, offset: 0 }
      },
      error: new Error('Network error')
    }
  ];

  render(
    <MockedProvider mocks={errorMocks}>
      <UsersList />
    </MockedProvider>
  );

  await waitFor(() => {
    expect(screen.getByText(/Error: Network error/)).toBeInTheDocument();
  });
});

The mock must match the query and variables exactly, otherwise the test gets an error. In Apollo Client 4 you import MockedProvider from @apollo/client/testing/react, and the addTypename option is gone: the cache always adds __typename to queries, so the mock data includes it too and normalization works like in production. The second test checks whether the error message reaches the screen.

When to Use Apollo Client?

Apollo Client shines when the backend uses GraphQL and you need a cache that normalizes and deduplicates data by itself. It helps with optimistic updates, for example a post like is visible immediately, with real-time data through subscriptions, and Apollo DevTools show the cache, queries and mutations in the browser. The alternatives are the lighter urql with a simpler API, React Query with the simple graphql-request client, and Relay from Meta, optimized for large applications. You will get to know React Query, meaning TanStack Query, in one of the next lessons.

Remember: Apollo Client is the ship's communications system, which not only receives signals, but also buffers them in the cache and distributes them to every module that needs them.

Code for this lesson: App.jsx
import React, { useState, useEffect } from 'react';

// Apollo Client simulation: queries, a mutation and a normalized cache
// In a real app this is done by ApolloClient, InMemoryCache, useQuery and useMutation

// Data on the GraphQL "server" side
let serverMissions = [
  { id: '1', name: 'Nebula Explorer', status: 'ACTIVE', crew: 12, progress: 78 },
  { id: '2', name: 'Dark Matter Probe', status: 'PLANNING', crew: 5, progress: 15 },
  { id: '3', name: 'Solar Flare Watch', status: 'COMPLETED', crew: 8, progress: 100 },
  { id: '4', name: 'Asteroid Mining Delta', status: 'ACTIVE', crew: 20, progress: 45 },
];
const serverCrew = [
  { id: '1', name: 'Commander Nova', role: 'command', missionId: '1' },
  { id: '2', name: 'Dr. Stellar', role: 'science', missionId: '1' },
  { id: '3', name: 'Astro-7', role: 'engineering', missionId: '2' },
  { id: '4', name: 'Ra', role: 'navigation', missionId: '4' },
];

const STATUS_LABELS = { ACTIVE: 'Active', PLANNING: 'Planning', COMPLETED: 'Completed', SUSPENDED: 'Suspended' };
const STATUS_COLORS = { ACTIVE: '#00ff88', PLANNING: '#ffa500', COMPLETED: '#64ffda', SUSPENDED: '#ff6b6b' };

// Normalized cache like InMemoryCache: every object is stored once under a Type:id key,
// and a query result keeps only a list of keys
const cache = { objects: new Map(), queries: new Map() };

function writeQuery(queryName, missions) {
  missions.forEach((mission) => cache.objects.set(`Mission:${mission.id}`, mission));
  cache.queries.set(queryName, missions.map((mission) => `Mission:${mission.id}`));
}

function readQuery(queryName) {
  const refs = cache.queries.get(queryName);
  return refs ? refs.map((ref) => cache.objects.get(ref)) : null;
}

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Query: the cache first, and the "network" only when data is missing
async function runQuery(queryName, variables = {}) {
  if (queryName === 'GET_MISSIONS') {
    const cached = readQuery('GET_MISSIONS');
    if (cached) return { data: cached, fromCache: true };
    await delay(800);
    writeQuery('GET_MISSIONS', serverMissions);
    return { data: readQuery('GET_MISSIONS'), fromCache: false };
  }
  if (queryName === 'GET_MISSION_CREW') {
    await delay(500);
    return { data: serverCrew.filter((member) => member.missionId === variables.id), fromCache: false };
  }
  throw new Error(`Unknown query: ${queryName}`);
}

// The mutation changes data on the server and returns an object with an id, so the cache
// replaces the Mission:id object, and every list with that key sees the new version
async function runMutation(mutationName, variables) {
  await delay(500);
  if (mutationName !== 'UPDATE_MISSION_STATUS') throw new Error(`Unknown mutation: ${mutationName}`);
  const mission = serverMissions.find((item) => item.id === variables.id);
  if (!mission) throw new Error(`Mission not found: ${variables.id}`);
  const updated = { ...mission, status: variables.status };
  serverMissions = serverMissions.map((item) => (item.id === updated.id ? updated : item));
  cache.objects.set(`Mission:${updated.id}`, updated);
  return { data: { updateMissionStatus: updated } };
}

// Hook simulating useQuery: returns loading, data and error
function useSimulatedQuery(queryName, variables = {}, refreshKey = 0) {
  const [state, setState] = useState({ loading: true, data: null, error: null, fromCache: false });
  const variablesKey = JSON.stringify(variables);

  useEffect(() => {
    let ignore = false;
    setState((prev) => ({ ...prev, loading: true }));
    runQuery(queryName, JSON.parse(variablesKey))
      .then((result) => {
        if (!ignore) setState({ loading: false, data: result.data, error: null, fromCache: result.fromCache });
      })
      .catch((error) => {
        if (!ignore) setState({ loading: false, data: null, error: error.message, fromCache: false });
      });
    return () => {
      ignore = true;
    };
  }, [queryName, variablesKey, refreshKey]);

  return state;
}

function MissionList({ selectedId, onSelect, refreshKey }) {
  const { loading, data, error, fromCache } = useSimulatedQuery('GET_MISSIONS', {}, refreshKey);

  if (loading && !data) return <div style={styles.loader}>Loading data from the GraphQL server...</div>;
  if (error) return <div style={styles.error}>Error: {error}</div>;

  return (
    <div style={styles.panel}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '8px' }}>
        <h3 style={styles.heading}>Space Missions</h3>
        <span style={fromCache ? styles.cacheBadge : styles.serverBadge}>{fromCache ? 'From cache' : 'From server'}</span>
      </div>
      {data.map((mission) => (
        <button
          key={mission.id}
          onClick={() => onSelect(mission.id)}
          style={{ ...styles.missionCard, borderColor: mission.id === selectedId ? '#00d4ff' : 'transparent' }}
        >
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: '8px' }}>
            <strong style={{ color: '#e0e1dd' }}>{mission.name}</strong>
            <span style={{ color: STATUS_COLORS[mission.status], fontSize: '12px' }}>{STATUS_LABELS[mission.status]}</span>
          </div>
          <div style={styles.progressBar}>
            <div style={{ ...styles.progressFill, width: `${mission.progress}%` }} />
          </div>
          <span style={{ color: '#8892b0', fontSize: '12px' }}>Crew: {mission.crew} | Progress: {mission.progress}%</span>
        </button>
      ))}
    </div>
  );
}

function MissionCrew({ missionId }) {
  const { loading, data } = useSimulatedQuery('GET_MISSION_CREW', { id: missionId });

  if (loading) return <p style={styles.muted}>Loading crew...</p>;
  if (data.length === 0) return <p style={styles.muted}>No crew assigned.</p>;
  return (
    <ul style={{ margin: '0 0 12px', paddingLeft: '18px', color: '#e0e1dd', fontSize: '13px' }}>
      {data.map((member) => (
        <li key={member.id}>{member.name} - {member.role}</li>
      ))}
    </ul>
  );
}

function MutationPanel({ selectedId, onMutated }) {
  const [mutating, setMutating] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);

  if (!selectedId) {
    return (
      <div style={styles.panel}>
        <h3 style={styles.heading}>GraphQL Mutations</h3>
        <p style={styles.muted}>Select a mission from the list to see its crew and change its status.</p>
      </div>
    );
  }

  const handleMutation = async (status) => {
    setMutating(true);
    setError(null);
    try {
      const { data } = await runMutation('UPDATE_MISSION_STATUS', { id: selectedId, status });
      const mission = data.updateMissionStatus;
      setResult(`${mission.name}: ${STATUS_LABELS[mission.status]}. The server returned an object with an id, so the cache replaced Mission:${mission.id}, and the list read it without a new query.`);
      onMutated();
    } catch (err) {
      setError(err.message);
    } finally {
      setMutating(false);
    }
  };

  return (
    <div style={styles.panel}>
      <h3 style={styles.heading}>GraphQL Mutations</h3>
      <p style={{ ...styles.muted, marginTop: 0 }}>Crew (query with an id variable):</p>
      <MissionCrew missionId={selectedId} />
      <p style={{ ...styles.muted, marginTop: 0 }}>Change status (mutation):</p>
      <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
        {Object.keys(STATUS_LABELS).map((status) => (
          <button key={status} onClick={() => handleMutation(status)} disabled={mutating}
            style={{ ...styles.btn, opacity: mutating ? 0.5 : 1 }}>
            {STATUS_LABELS[status]}
          </button>
        ))}
      </div>
      {mutating && <p style={styles.muted}>Sending the mutation...</p>}
      {result && !mutating && <p style={{ color: '#00ff88', fontSize: '13px', marginTop: '10px' }}>{result}</p>}
      {error && <p style={styles.error}>{error}</p>}
    </div>
  );
}

function App() {
  const [selectedMission, setSelectedMission] = useState(null);
  const [refreshKey, setRefreshKey] = useState(0);

  return (
    <div style={styles.container}>
      <h1 style={styles.title}>Apollo Client - GraphQL Mission Control</h1>
      <p style={styles.subtitle}>Simulation of queries, mutations and a normalized cache</p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '16px' }}>
        <MissionList selectedId={selectedMission} onSelect={setSelectedMission} refreshKey={refreshKey} />
        <MutationPanel key={selectedMission} selectedId={selectedMission} onMutated={() => setRefreshKey((key) => key + 1)} />
      </div>
      <p style={styles.note}>After a mutation the list shows the "From cache" badge: the new status came in the mutation response and went into the cache, so the GET_MISSIONS query did not have to ask the server. In Apollo Client, useQuery would refresh the list by itself, because it watches the cache.</p>
    </div>
  );
}

const styles = {
  container: { minHeight: '100vh', background: 'linear-gradient(135deg, #0d1b2a 0%, #1a1a3e 100%)', padding: '24px 16px', color: '#e0e1dd', fontFamily: 'system-ui, sans-serif', boxSizing: 'border-box' },
  title: { textAlign: 'center', color: '#00d4ff', margin: '0 0 4px', fontSize: '24px' },
  subtitle: { textAlign: 'center', color: '#8892b0', marginBottom: '20px' },
  panel: { background: 'rgba(0,0,0,0.3)', borderRadius: '12px', padding: '16px', border: '1px solid rgba(0,212,255,0.2)' },
  heading: { color: '#00d4ff', margin: '0 0 12px', fontSize: '17px' },
  missionCard: { display: 'block', width: '100%', textAlign: 'left', padding: '12px', background: 'rgba(0,0,0,0.3)', borderRadius: '8px', marginBottom: '8px', cursor: 'pointer', border: '1px solid transparent', color: 'inherit', font: 'inherit' },
  progressBar: { height: '6px', background: 'rgba(255,255,255,0.1)', borderRadius: '3px', margin: '8px 0' },
  progressFill: { height: '100%', background: 'linear-gradient(90deg, #00d4ff, #00ff88)', borderRadius: '3px', transition: 'width 0.3s' },
  cacheBadge: { background: '#00ff88', color: '#0d1b2a', padding: '2px 8px', borderRadius: '4px', fontSize: '11px', fontWeight: 'bold', whiteSpace: 'nowrap' },
  serverBadge: { background: 'rgba(0,212,255,0.2)', color: '#00d4ff', padding: '2px 8px', borderRadius: '4px', fontSize: '11px', fontWeight: 'bold', whiteSpace: 'nowrap' },
  loader: { color: '#8892b0', textAlign: 'center', padding: '40px' },
  error: { color: '#ff6b6b', fontSize: '13px' },
  muted: { color: '#8892b0', fontSize: '13px' },
  btn: { padding: '8px 12px', background: 'rgba(0,212,255,0.15)', border: '1px solid #00d4ff', borderRadius: '6px', color: '#00d4ff', cursor: 'pointer', fontSize: '12px' },
  note: { maxWidth: '760px', margin: '16px auto 0', color: '#8892b0', fontSize: '13px', lineHeight: 1.5 },
};

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What role does InMemoryCache play in Apollo Client?

  2. 2. How does the useMutation hook differ from useQuery in Apollo Client?

Hands-on tasks in the game

  • Click in order

    Click the elements in the order from the lesson: the useQuery call, handling loading, handling the error and displaying the data:

  • Click in order

    Arrange the syntax for using the useQuery hook with Apollo Client:

  • Horizontal ordering

    Arrange the elements of a useQuery call in Apollo Client from left to right:

  1. Click in orderuseQuery State Handling
  2. QuestionApollo Client - Cache
  3. Click in orderApollo useQuery Syntax
  4. QuestionThe useMutation Hook in Apollo Client
  5. Put in orderuseQuery Syntax in Apollo Client

Useful articles