Apollo Client

A collection of Apollo Client code snippets.

useQuery

Basic example of using useQuery hook from Apollo Client.

apollo-use-query.tsx
import { gql, useQuery } from "@apollo/client";

// GraphQL query.
const BLOG_POST_QUERY = gql`
  query BlogPostQuery($id: String) {
    blog(id: $id) {
      id
      title
      description
    }
  }
`;

export default function BlogPostPage() {
  const { loading, error, data } = useQuery(BLOG_POST_QUERY, {
    variables: {
      id: uuid,
    },
  });

  // Error state.
  if (error) {
    return <div>Something went wrong.</div>;
  }

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

  return (
    <div id={data.blog.id}>
      <h1>{data.blog.title}</h1>
      <p>{data.blog.description}</p>
    </div>
  );
}

useLazyQuery

Basic example of using useLazyQuery hook from Apollo Client.

apollo-use-lazy-query.tsx
import { gql, useLazyQuery } from "@apollo/client";

const QUERY = gql`
  query ($id: String) {
    blog(id: $id) {
      id
      title
      description
    }
  }
`;

export default function FormExample() {
  // Hooks must always be top level.
  const [runLazyQuery, { loading, data, error }] = useLazyQuery(
    QUERY,
    variables: {
      id: uuid
    },
  );

  function handleSubmit() {
    runLazyQuery();
    // Do something with data returned by query . . .
  }

  return (
    <form
      id="form"
      onSubmit={handleSubmit}
    >
      {/* Form fields go here */}
    </form>
  )
}