SyntaxStudy
Sign Up
GraphQL Apollo Client: Queries and Mutations
GraphQL Beginner 1 min read

Apollo Client: Queries and Mutations

Apollo Client is a state management library that integrates GraphQL with React, Vue, and Angular. Its InMemoryCache normalizes query results by __typename + id, so components that display the same object stay in sync automatically when any mutation updates it. The useQuery hook manages loading, error, and data states and handles polling and refetching. The useMutation hook returns a mutation function and its execution state. Both hooks integrate with React's rendering lifecycle, re-rendering the component only when the relevant cached data changes.
Example
// npm install @apollo/client graphql

import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery, useMutation } from '@apollo/client';

// 1. Create client
const client = new ApolloClient({
  uri: 'https://api.example.com/graphql',
  cache: new InMemoryCache(),
  headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
});

// 2. Wrap app
function App() {
  return <ApolloProvider client={client}><Posts /></ApolloProvider>;
}

// 3. Query hook
const GET_POSTS = gql`
  query GetPosts($limit: Int!) {
    posts(first: $limit) {
      edges { node { id  title  author { name } } }
    }
  }
`;

function Posts() {
  const { loading, error, data, refetch } = useQuery(GET_POSTS, {
    variables: { limit: 10 },
    pollInterval: 30000,   // auto-refresh every 30s
  });
  if (loading) return <p>Loading…</p>;
  if (error)   return <p>Error: {error.message}</p>;
  return data.posts.edges.map(({ node }) => <div key={node.id}>{node.title}</div>);
}

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

function NewPostForm() {
  const [createPost, { loading }] = useMutation(CREATE_POST, {
    refetchQueries: [{ query: GET_POSTS, variables: { limit: 10 } }],
  });
  const submit = (title) => createPost({ variables: { input: { title, body: '...' } } });
  return <button onClick={() => submit('New Post')} disabled={loading}>Add</button>;
}