Apollo Client with React

◕ GraphQLLesson 10Intermediate

Apollo Client is the leading state management library for consuming GraphQL APIs in React. It handles fetching, caching, and synchronizing data from your GraphQL server with your React components.

1 Setup
Terminal — Install Apollo Client
npm install @apollo/client graphql
JavaScript — Apollo Client Setup (main.jsx)
import { ApolloClient, InMemoryCache, ApolloProvider, createHttpLink } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";

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

// Attach JWT token to every request
const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("token");
  return {
    headers: { ...headers, authorization: token ? "Bearer " + token : "" }
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

ReactDOM.createRoot(document.getElementById("root")).render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);
2 useQuery & useMutation Hooks
JavaScript — React Component with Apollo Hooks
import { useQuery, useMutation, gql } from "@apollo/client";

const GET_POSTS = gql`
  query GetPosts($limit: Int) {
    posts(limit: $limit) {
      id title
      author { name }
      commentCount
    }
  }
`;

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

function PostList() {
  const { loading, error, data } = useQuery(GET_POSTS, {
    variables: { limit: 10 }
  });

  const [createPost, { loading: creating }] = useMutation(CREATE_POST, {
    // Automatically refetch posts after mutation
    refetchQueries: [{ query: GET_POSTS, variables: { limit: 10 } }]
  });

  if (loading) return <p>Loading...</p>;
  if (error)   return <p>Error: {error.message}</p>;

  return (
    <div>
      {data.posts.map(post => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>by {post.author.name}</p>
        </div>
      ))}
    </div>
  );
}
3 Code Challenge
Challenge: Build a React component that uses useQuery to list products with a category filter dropdown, and useMutation to add a new product via a form. Use Apollo cache update (cache.modify) instead of refetching to update the list after creation.