Thuta Learning
GraphQL
ProjectsWeb Developmentbeginner

Project 2 — Apollo Client with React

What you'll walk away with

  • Explain the core ideas behind Project 2 — Apollo Client with React
  • Run the sample GraphQL query or code and verify its output
  • Apply the technique correctly to the Tutorial Platform and production scenarios

Build the mental model

Apollo Client exposes React hooks (`useQuery`, `useMutation`) to fetch and update GraphQL data inside components, with a single hook managing loading, error, and data states. Its InMemoryCache normalizes response objects by `__typename` plus `id`, so when two queries return the same object, they share one cached copy — updating that object from a mutation can automatically sync every screen showing it.

Connect it to a real scenario

Build the Tutorial Platform blog frontend's `PostList` component by fetching `GET_POSTS` with `useQuery`. Call `ADD_COMMENT` with `useMutation` and, on success, refresh the post list automatically using `refetchQueries` or a cache-update function.

Try the working example

tsx
const GET_TUTORIALS = gql`
  query GetTutorials {
    tutorials {
      id
      title
    }
  }
`;

function TutorialList() {
  const { data, loading, error } = useQuery(GET_TUTORIALS);
  if (loading) return <p>Loading...</p>;
  if (error) return <p>{error.message}</p>;
  return (
    <ul>
      {data.tutorials.map((t: { id: string; title: string }) => (
        <li key={t.id}>{t.title}</li>
      ))}
    </ul>
  );
}
You should see
You can read data with `useQuery` and write data with `useMutation` inside a React component.

5-minute try-it

Call the `ADD_COMMENT` mutation with `useMutation` and wire its loading state to disable the submit button.

One important caution

Omitting the `id` field from a query means InMemoryCache cannot normalize that object, causing cache misses or duplicated data — always include `id` in your queries.

Apollo Client — Get StartedGraphQL

Easy traps

  • Omitting the `id` field from a query means InMemoryCache cannot normalize that object, causing cache misses or duplicated data — always include `id` in your queries.
  • Validate sample queries and mutations on a local or test server with recoverable data before applying them to production.

Exercise

Call the `ADD_COMMENT` mutation with `useMutation` and wire its loading state to disable the submit button.

You'll know it worked when: You can read data with `useQuery` and write data with `useMutation` inside a React component.