- Date
Using WPGraphQL with Apollo Client
React CodeSandbox demo: https://codesandbox.io/s/wpgraphql-apollo-demo-cvg8n
The Apollo Client library is one of the most popular options to manage local and remote data with GraphQL. Developers love it because of the caching and query/mutation abstractions.
Interacting with the Apollo package with WPGraphQL works out-of-the-box.
This tutorial is with React, but many of the principles should work, depending on your framework of choice.
Set up Apollo in your application
Step 1: install Apollo
Install the Apollo Client package via npm in your terminal:
npm install @apollo/client
Step 2: create an Apollo component and instantiate a new ApolloClient instance
The Apollo Client needs to be instantiated with a few options. Create a component and instantiate the instance, passing along your WPGraphQL endpoint along with the basic caching options:
import { ApolloClient, InMemoryCache } from "@apollo/client";
const client = new ApolloClient({
uri: "https://demo.wpgraphql.com/graphql",
cache: new InMemoryCache(),
});
export default client;
Step 3: wrap your application with the ApolloProvider
Now that we’ve instantiated the Apollo Client instance, we need to wrap our root application, passing into it the client class we previously created. Therefore, all child components will have access to the same Apollo store to query/mutate to our previously established WPGraphQL endpoint.
import React from "react";
import { ApolloProvider } from "@apollo/client";
import client from "./apollo";
export default function App() {
return (
...
)
Write your query
The Apollo 3 API simplified how consumers write their queries. In keeping inline with React hooks, Apollo exposes a `useQuery` hook for us.
Note: this query runs when the component mounts. If you’re looking for more control, check out the useLazyQuery() hook. Reference: https://www.apollographql.com/docs/react/api/react/hooks/#uselazyquery
import { useQuery, gql } from "@apollo/client";
import React from "react";
const Posts = () => {
const { data, loading, error } = useQuery(QUERY_POSTS);
if (error) return Error! {error.message}
;
if (loading) return Loading...
;
return (
{data.posts.edges.map(({ node }) => (
))}
);
};
const QUERY_POSTS = gql`
query GetPosts {
posts(first: 12) {
edges {
node {
id
title
}
}
}
}
`;
export default Posts;
Conclusion
And there we have it. Now you can make run-time graphql requests with Apollo to your WPGraphQL API. While the example is a bit contrived, the foundation is something we can build off of: whether that’s writing mutations to create comments, our building our a rich UI filter system.
Video tutorial example for using WPGraphQL with Apollo Client