Using Apollo / GraphQL with Vue.js

Joshua Bemenderfer

GraphQL has taken the world by storm lately. Originally made for Facebook’s specialized use-cases, it has spread across the development scene to become what is now arguably the most preferred method of client-server data transfer. At the forefront of GraphQL innovation is Apollo, an independent group of systems for creating GraphQL clients and servers. Today we’ll learn how to integrate apollo-client 2 with Vue.js using vue-apollo.

Installation

Now, unfortunately, apollo-client has a number of dependencies and can be a pain to set up. I’ll walk you through it.

# Yarn
$ yarn vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-link-context apollo-cache-inmemory graphql-tag
# NPM
$ npm install --save vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-link-context apollo-cache-inmemory graphql-tag

Usage

Most likely, you already have a project set up with Vue if you’re intending to add GraphQL / Apollo to it, but if not, what we’re doing here will be based off of the webpack-simple template.

Now we have to set up Apollo in main.js. There are a number of steps worth explaining, so I’ll break it down into chunks.

main.js (Imports)

import Vue from 'vue';
import App from './App.vue';

// This is everything we need to work with Apollo 2.0.
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import VueApollo from 'vue-apollo';

// Register the VueApollo plugin with Vue.
Vue.use(VueApollo);

Now, we must create the HTTP Link for Apollo. Apollo 2.0 was designed to have a pluggable transport / link system, so you could load a GraphQL API from websockets, or other modes of transport. For some reason, those modes are called “links”. Don’t let the terminology confuse you. :)

main.js (Apollo Link)

// Create a new HttpLink to connect to your GraphQL API.
// According to the Apollo docs, this should be an absolute URI.
const httpLink = new HttpLink({
  uri: `https://somerandomgraphqlapi.com/api`
});

// I'm creating another variable here just because it makes it easier to add more links in the future.
const link = httpLink;

Once that’s done, we need to set up the Apollo Client.

main.js (Apollo Client)

// Create the apollo client
const apolloClient = new ApolloClient({
  // Tells Apollo to use the link chain with the http link we set up.
  link,
  // Handles caching of results and mutations.
  cache: new InMemoryCache(),
  // Useful if you have the Apollo DevTools installed in your browser.
  connectToDevTools: true,
});

Alright, now we need to tell Vue & VueApollo about apolloClient.

main.js (VueApollo Setup)

const apolloProvider = new VueApollo({
  // Apollo 2.0 allows multiple clients to be enabled at once.
  // Here we select the default (and only) client.
  defaultClient: apolloClient,
});

new Vue({
  // Inject apolloProvider for components to use.
  provide: apolloProvider.provide(),
  render: h => h(App),
}).$mount('#app');

And that’s all you need to get Apollo set up in your Vue app. See below for the full code and some tips. In the next section we’ll demonstrate how to use it.

Complete main.js

import Vue from 'vue';
import App from './App.vue';
// This is everything we need to work with Apollo 2.0.
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import VueApollo from 'vue-apollo';

// Register the VueApollo plugin with Vue.
Vue.use(VueApollo);

// Create a new HttpLink to connect to your GraphQL API.
// According to the Apollo docs, this should be an absolute URI.
const httpLink = new HttpLink({
  uri: `https://somerandomgraphqlapi.com/api`
});

// I'm creating another variable here just because it
// makes it easier to add more links in the future.
const link = httpLink;

// Create the apollo client
const apolloClient = new ApolloClient({
  // Tells Apollo to use the link chain with the http link we set up.
  link,
  // Handles caching of results and mutations.
  cache: new InMemoryCache(),
  // Useful if you have the Apollo DevTools installed in your browser.
  connectToDevTools: true,
});

const apolloProvider = new VueApollo({
  // Apollo 2.0 allows multiple clients to be enabled at once.
  // Here we select the default (and only) client.
  defaultClient: apolloClient,
});

new Vue({
  // Inject apolloProvider for components to use.
  provide: apolloProvider.provide(),
  render: h => h(App),
}).$mount('#app');

Modifying HTTP Headers for Authentication

Often times you’ll need access to the HTTP requests made by Apollo before they’re sent. For example, in order to add JWT authentication headers. This can be done by adding an extra link using setContext. (This is what the dependency on apollo-link-context is for. I’ve never not had to use it.)

main.js

// Add this to your Apollo imports.
import { setContext } from 'apollo-link-context';

...

// Create a new Middleware Link using setContext
const middlewareLink = setContext(() => ({
  headers: {
    authorization: `Bearer ${HOWEVER_I_GET_MY_JWT}`
  }
}));

// Change your link assignment from
// const link = httpLink;
// to
const link = middlewareLink.concat(httpLink);

Making GraphQL Queries

Now, in your components, you can make queries and have them auto-populate component data like so:

MyComponent.vue

<template>
  <p v-if="alligatorGraphQL">From GraphQL: {{alligatorGraphQL.name}}</p>
</template>

<script>
import gql from 'graphql-tag';

export default {
  data() {
    return {
      <span class="code-annotation">alligatorGraphQL: null</span>
    }
  },

  apollo: {
    // They key is the name of the data property
    // on the component that you intend to populate.
    alligatorGraphQL: {
      // Yes, this looks confusing.
      // It's just normal GraphQL.
      query: gql`
        query alligatorQuery($input: String!) {
          getAlligator(uuid: $input) {
            name
          }
        }
      `,

      variables: {
        // Some random UUID I generated.
        input: `03e082be-5e10-4351-a968-5f28d3e50565`
      },

      // Apollo maps results to the name of the query, for caching.
      // So to update the right property on the componet, you need to
      // select the property of the result with the name of the query.
      update: result => result.getAlligator,
    }
  }
}

(This assumes your server-side schema is roughly as follows:)

type Alligator {
  name: String
}

type Query {
  getAlligator(uuid: String!): Alligator
}

type Mutation {
  updateAlligatorName(name: String!): String
}

schema {
  query: Query
  mutation: Mutation
}

Protip: Almost any property of apollo {} on a Vue component can be reactive. So if you want to change variables or queries based on a reactive property, just replace the object with a function that returns an object based on the component data.

Making GraphQL Mutations

Let’s go ahead and modify the component above so that we can update the name of the Alligator as well as read it. For this we’ll need GraphQL mutations.

MyComponent.vue

<template>
  <p>
    Alligator Name:
    <input type="text" v-if="alligatorGraphQL"
      :value="alligatorGraphQL.name" @input="temporaryName = $event.target.value"
    />
    <button @click="updateName">Update Name</button>
  </p>
</template>

<script>
import gql from 'graphql-tag';

export default {
  data() {
    return {
      temporaryName: '',
      alligatorGraphQL: null
    }
  },

  apollo: {
    alligatorGraphQL: {
      query: gql`
        query alligatorQuery($input: String!) {
          getAlligator(uuid: $input) {
            name
          }
        }
      `,

      variables: {
        input: `03e082be-5e10-4351-a968-5f28d3e50565`
      },

      update: result => result.getAlligator,
    }
  },

  methods: {
    updateName() {
      this.$apollo.mutate({
        mutation: gql`
          mutation ($name: String!) {
            updateAlligatorName(name: $name)
          }
        `,
        variables: { name: this.temporaryName }
      }).then(mutationResult => {
        // Do stuff with the result.
        console.log(`The Alligator's updated name is: ${mutationResult.data.updateAlligatorName}`)
      });

    }
  }
}
</script>

You’ll probably notice that we’re using a temporary variable instead of v-model here or two-way binding. This is because Apollo’s data results are read-only and immutable. So basically anything you get from your GraphQL server will need to be either manipulated or handled as an immutable resource.

There you go! Your mutation should now fire and make the necessary changes on the server. (Provided the server is configured correctly, that is.)

That’s all you need to get started with Vue and Apollo. For more details, see the documentation on apollo-vue and Apollo.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#