Apollo Client is the most popular GraphQL client currently available in the JavaScript ecosystem. In this article we’ll see how to install it and use it in Vue.js.
Installation and Configuration
Installation consists of adding the two essential NPM packages:
npm install @apollo/client graphql --save
Next, let’s add a variable to our .env
file containing the endpoint of our GraphQL API:
VITE_API_URL=https://example.com/graphql
Create the Client
We can now create a file containing the instance of our client so we can use it to perform queries and mutations.
// src/api/client.js
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
link: new HttpLink({
uri: import.meta.env.VITE_API_URL,
}),
cache: new InMemoryCache(),
});
export default client;
If our API is protected by an authorization token, we need to include it in the headers of the client instance.
// src/api/client.js
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
link: new HttpLink({
uri: import.meta.env.VITE_API_URL,
headers: {
authorization: localStorage.getItem('auth-token') || '',
},
}),
cache: new InMemoryCache(),
});
export default client;
Query
To perform a query on our API, we can use the client’s query()
method. If our query contains variables, they must be specified as properties of the variables
object inside the method. The query
property uses an instance of the gql
package to convert the query string.
// src/api/posts.js
import client from './client';
import { gql } from '@apollo/client';
export const getPosts = async (page = 1) => {
const results = await client.query({
query: gql`
query posts($page: Int) {
posts(page: $page) {
id
title
body
}
}
`,
variables: {
page: page,
},
});
return {
posts: results.data.posts
};
};
Mutation
To perform a mutation we can use the client’s mutate()
method. The syntax is similar to what we saw for queries, except that we use the mutation
property instead of query
.
export const deletePost = async (id) => {
const results = await client.mutate({
mutation: gql`
mutation deletePost($id: ID!) {
deletePost(id: $id) {
id
}
}
`,
variables: {
id: id,
},
});
return results;
};
Conclusion
Apollo Client proves to be an excellent solution for interacting with GraphQL APIs in Node.js. Its ease of configuration and use make it a recommended choice for Vue.js.