How to use GraphQL in Vue3 with the Apollo Client

Integrate GrapghQL with Vue3 using the Vue-apollo library (Composition API).

Leonid Shvab
JavaScript in Plain English

--

The featured image for the article. How to use GraphQL in Vue3 with the Apollo Client
The featured image for the article

Plan:
1. What is a GraphQL or Apollo client?
2. Practice part.
2.1. Set up the Apollo-client (composition API).
2.2. Look into the free GraphQL API.
2.3. How to get data from a GraphQL server (queries).
2.4. How to send data to a GraphQL server (mutations).
2.5. Fetch Policy.
2.6. How to open the channel between client and server (subscriptions).
3. Useful links and an example on GitHub.

1. What is GraphQL or Apollo Client?

GraphQL is a query language for APIs, it provides one of the options to communicate between back-end and front-end.
One of the advantages of GraphQL is the optimization of data transfer from server to client. So this technology allows receiving only necessary data. One of the disadvantages is the complexity and cost of implementation.
And one interesting fact: when you work with GraphQL, you send all requests to one endpoint but with different options via the POST method.

Apollo Client is a popular library for working with GraphQL. It provides more convenient tools for working with GraphQL.

Weekly Apollo Client download statistics via npm. Almost, 2900 0000 downloads in week
Weekly Apollo Client download statistics via npm

2. Practice part

2.1. Set up the Apollo-client (composition API)

Firstly, you need to install the necessary basic packages.

npm install --save graphql graphql-tag @apollo/client

// or

yarn add graphql graphql-tag @apollo/client

Then you need to install a package for working with the composition API approach.

npm install --save @vue/apollo-composable

// or

yarn add @vue/apollo-composable

For option API, you need to choose another one [vue-apollo-option].

Back to work with composition API. Then you need to set up Apollo in your main.js.

// main.js
import App from './App.vue'

import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client/core'
import { DefaultApolloClient } from '@vue/apollo-composable'

const httpLink = createHttpLink({
uri: 'https://spacex-production.up.railway.app/',
})

const cache = new InMemoryCache()

const apolloClient = new ApolloClient({
link: httpLink,
cache,
})

const app = createApp({
setup() {
provide(DefaultApolloClient, apolloClient)
},

render: () => h(App),
})

app.mount('#app')

2.2. Look through the free GraphQL API

Free SpaceX graphQL API — documentation
Free SpaceX graphQL API — playground

It will help you better understand the syntax of GraphQL queries and what requests from this article will do.

Free SpaceX graphQL API example — playground. gif file that shows the playground for working with the api
Free SpaceX graphQL API example — playground

2.3. How to get data from the GraphQL server (queries)

Queries are used to get data from the server.

<template>
<p v-show="loading">Loading..</p>

<p v-if="result">result: {{ result }}</p>
<p v-else-if="error">error: {{ error }}</p>
</template>

<script setup>
import gql from "graphql-tag"
import { useQuery } from "@vue/apollo-composable"

const QUERY_COMPANY_INFO = gql`
query Company {
company {
founded
founder
name
summary
}
}
`

const { result, loading, error } = useQuery(QUERY_COMPANY_INFO)
</script>

useQuery is a composition function for executing queries. It returns some properties and methods: result, loading, error, variables, networkStatus, document, fetchMore, onError…
gql is an operation for defining GraphQL queries, mutations, and subscriptions.
Inside gql is a query from the Free SpaceX graphQL API — playground.

Also, you can send some parameters (variables) in a request to the server, for instance, if you need to get the exact user.

const { result, loading, error } = useQuery(QUERY_USER, { id: '120321' })

Also, you can use your custom variable name instead of result.

const { result: user } = useQuery(QUERY_USER, { id: '120321' })

2.4. How to send data to the GraphQL server (mutations)

Let’s study how to update data on the server using mutations.

<template>
<button @click="mutate">
Send message
</button>
</template>

<script setup>
import gql from "graphql-tag"
import { useMutation } from "@vue/apollo-composable"

const MUTATE_INSERT_USERS = gql`
mutation Mutation($objects: [users_insert_input!]!) {
insert_users(objects: $objects) {
affected_rows
returning {
id
name
timestamp
}
}
}
`

const { mutate } = useMutation(
MUTATE_INSERT_USERS,
{ variables: necessaryData }
)
</script>

useMutation is a composition function for executing mutations. It returns some properties and methods: mutate, loading, error, called, onDone, onError.

gql is an operation for defining GraphQL queries, mutations, subscriptions.
Inside gql is a query from the Free SpaceX graphQL API — playground.

2.5. Fetch Policy [example from documentation]

  • cache-first (default): return result from cache(if it exists). Only fetch from network if cached result is empty[can be skipped].
  • cache-and-network: return result from cache first (if it exists), then return from network[both steps].
  • cache-only: return result from cache (if it exists), fail otherwise.
  • network-only: return result from network, save to cache.
  • no-cache: return result from network, don't save to cache.

We can pass options with Fetch Policy to useQuery as the 3rd parameter but variables as the 2nd parameter.

const { result } = useQuery(
QUERY_COMPANY_INFO,
{ ...variables },
{
fetchPolicy: 'network-only',
}
)

We can pass options with fetchPolicy and variables to useMutation as the 2nd parameter

const { result } = useMutation(
MUTATE_INSERT_USERS,
{
fetchPolicy: 'no-cache',
variables: necessaryData,
}
)

2.6. How to open the channel between client and server (subscriptions)

Subscription is an analog of WebSocket.
Subscriptions provide us with the opportunity to open a channel between the client and server and transfer data between them in real-time.

The subscription needs additional configuration, see the documentation.

const variables = reactive({
channelId: "abc"
})

const { result } = useSubscription(
gql`
subscription onMessageAdded($channelId: ID!) {
messageAdded(channelId: $channelId) {
id
text
}
}
`,
variables,
() => ({
fetchPolicy: "no-cache"
})
)

The syntax is very similar to useQuery

3. Useful links and an example on GitHub

3.1. Short example on Github
3.2. API for this article
3.3. Install the basic vue apollo client for vue3.
3.4. Prepare for working with the option API vue/apollo-option.
3.5. Prepare for working with the composition API vue/apollo-composable.
3.6. GraphQL in general.
3.7. Free GraphQL APIs.
3.8. Integrate graphQL with Vue (option api)

Home task: fork and clone the project, make a new git branch, try to get a list of dragons, then, by clicking on an item of the list, get all information about the dragon by ID, and show the modal with information about this dragon. Make a pull request and add PR to the comments.

In Plain English

Thank you for being a part of our community! Before you go:

--

--