Apollo Client

A collection of Apollo Client code snippets.

William Luisi
William Luisi
Dec 19, 2021 - 11:30AM
Engineering
ReactJS

useQuery

Basic example of using useQuery hook from Apollo Client.

apollo-use-query.tsx
1import { gql, useQuery } from "@apollo/client";
2
3// GraphQL query.
4const BLOG_POST_QUERY = gql`
5 query BlogPostQuery($id: String) {
6 blog(id: $id) {
7 id
8 title
9 description
10 }
11 }
12`;
13
14export default function BlogPostPage() {
15 const { loading, error, data } = useQuery(BLOG_POST_QUERY, {
16 variables: {
17 id: uuid,
18 },
19 });
20
21 // Error state.
22 if (error) {
23 return <div>Something went wrong.</div>;
24 }
25
26 // Loading state.
27 if (loading) {
28 return <div>Loading . . .</div>;
29 }
30
31 return (
32 <div id={data.blog.id}>
33 <h1>{data.blog.title}</h1>
34 <p>{data.blog.description}</p>
35 </div>
36 );
37}

useLazyQuery

Basic example of using useLazyQuery hook from Apollo Client.

apollo-use-lazy-query.tsx
1import { gql, useLazyQuery } from "@apollo/client";
2
3const QUERY = gql`
4 query ($id: String) {
5 blog(id: $id) {
6 id
7 title
8 description
9 }
10 }
11`;
12
13export default function FormExample() {
14 // Hooks must always be top level.
15 const [runLazyQuery, { loading, data, error }] = useLazyQuery(
16 QUERY,
17 variables: {
18 id: uuid
19 },
20 );
21
22 function handleSubmit() {
23 runLazyQuery();
24 // Do something with data returned by query . . .
25 }
26
27 return (
28 <form
29 id="form"
30 onSubmit={handleSubmit}
31 >
32 {/* Form fields go here */}
33 </form>
34 )
35}