How to connect your GraphQL API to your VueJS Frontend

Marion Schleifer
8 min readMar 19, 2019

--

I recently wrote a blogpost about how to create an API with Hasura’s GraphQL engine. If you are not familiar with GraphQL yet, I recommend reading this post first. Now, we will build a very simple Vue app and we’ll learn how connect it to our GraphQL API.

If something is unclear during the creation of the Vue app or if you want to see the full solution, you can always view the project on Github.

Table of Contents

Creating a Vue project

Let’s create a Vue project in our terminal by running:

vue create harry-potter-app

Select the default preset and open the project in your favourite editor. In order to make the appearance of our app a little prettier, we add the Milligram library. In the public index.html, add these three lines inside the <head>:

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic"><link rel="stylesheet" href="//cdn.rawgit.com/necolas/normalize.css/master/normalize.css"><link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">

Go to your terminal, cd into your project, and run your application by typing locally:

With yarn:

yarn serve

With npm:

npm run serve

You should see Vue’s Hello World page with the Vue logo:

When we look at our Harry Potter API that we created in the previous post, we can see that we have several tables: movies, characters, actors and scenes. What we want to in our Vue app is to create components for movie. In the end, we want a component for a list of movies that consists of several components that represent a single movie. And we want to create a component that allows us to add movies.

Movie list component

Let’s get started. First, we’ll register the MoviesList component to the App.vue file. Inside the file, we need to replace the <HelloWorld/> component with <movies-list/>. Now this will fail, because we haven’t registered our new component. A little further down in the same file in the components list, let’s import our renamed component from the right location and replace the HelloWorld component with the MoviesList component. When you’re done, it should look like this:

Now, we need to rename the HelloWorld.vue file to MoviesList.vue. Inside the file, we’ll replace the <template> and the <script> so it looks like this:

Let me explain what happens here. Inside the template, we add a <div> that iterates over all our movies with v-for. We have to tell Vue how to identify each movie, which we’ll do by their id. Using the double curly braces, we tell Vue what to display in the browser, which is in our case the id of the movies. Inside the <script> tag, we define what data should be displayed. For now, we display dummy data which is a movie with an ID that we defined. If you now look at the app in your browser, you’ll see the Vue logo and the id of the movie.

Movie detail component

As we said before, we also need a component to display one movie. The purpose of this being that we can later display a collection of actual MovieItems in the MoviesList, instead of using dummy data. So let’s go ahead and inside the components folder, let’s create a new file called MovieItem.vue. For each MovieItem in the MoviesList, we want to display the title, the director, the composer and the release date. So let’s go ahead and add the component to the MovieItem.vue file.

Now, we’ll have to go back to MoviesList.vue, and change it, so that we can display the actual MovieItems in our list.

In order to do so, we need to change line 3 to use the <movie-item> component instead of a simple <div>. Also, in line 8, we need to import the MovieItem from its corresponding file. Finally, in line 11, we need to state that MovieItem is the component that is used inside the current file as an instance of a list of movies.

When you now refresh your browser, it should look like this:

Add movie component

Let’s now add the capability to add new movies to our application. In order to do so, inside the components folder, we’ll create a new file called AddMovie.vue and leave it empty for now. Now we’ll open App.vue and inside the <template>, we’ll add the <add-movie/> component before the <movies-list> component. Also, like with the MoviesList component, we need to import the component from the correct location and add the AddMovies component to our components list. When you’re done, your <template> and <script> should look like this:

Inside the AddMovie.vue file, we’ll add a form to create new movies. When we have a look at our API, we can see what fields the movie table has. For now, we want to be able to create a movie that has a title, a director, a composer and a release date. The file should look like this:

It is a very simple form that allows us to enter the fields for a movie and submit. Note that we haven’t added any methods to the component yet, so nothing happens if we click the submit button.

When you refresh your browser, you should see this:

Connecting to GraphQL API

The next step is to connect our Vue app to our GraphQL API that we created in the last post, so that we can display actual data instead of dummy data. Let’s go ahead and get started.

In the previous post, we’ve seen how we can run queries in the GraphiQL tool. We can go to the Hasura console and in GraphiQL, let’s test the methods to get a list of all movies, as well as the functionality to add a new movie:

Now, in from Vue project, we want to invoke exactly these methods. In order to do that, we will use the Apollo client. Apollo is a GraphQL platform that allows you to make queries to your API in a simplified language. Let’s install Apollo by running this command in the command line (in your project folder):

with npm:

npm install apollo-client apollo-cache-inmemory apollo-link-http graphql-tag graphql --save

with yarn:

yarn add vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-cache-inmemory graphql-tag

First, we need to establish the link to our Hasura project and to instantiate Apollo. Change your main.js so it looks as follows.

Let’s go through this. First, we need to import the libraries we just installed, because we will use them in this file. Using HttpLink, we establish a connection to our GraphQL API on lines 12–14. You find your own custom link in the GraphiQL tool on your Hasura project:

Next, in lines 16–20, we create an instance of the ApolloClient. As arguments, we pass our HttpLink, so that the data gets polled from the correct API. Next, we pass our cache. InMemoryCache is the default cache implementation for ApolloClient, so we use this one. Finally, we pass the option to connect to dev tools, so that we get an Apollo tab in our chrome inspector in case we have to debug.

On line 22, we configure our Vue instance to use VueApollo.

In order to to be able to make queries and mutations from our Vue app, we need to create an instance of ApolloProvider (lines 24–26). We’ll pass it our Apollo client with which we will commit these operations.

Finally, on lines 28–32, we launch our Vue app where our Apollo provider is passed, so that we can make database queries and manipulations throughout our app.

Fetch actual data from GraphQL API

So far, we’ve been displaying dummy data in our Vue frontend. Now, we want to display actual data. In our MoviesList, we want to display the movies that are currently stored in our database. Also, we want to be able to add movies, so that they get saved in our database and displayed in our frontend.

Movies list

In order to display movies from our database, let’s change MoviesList.vue to the following:

Inside the <script> tag, we need to import GraphQL, which will allow us to make queries. On lines 11–21, we define the GraphQL query to retrieve the list of movies.

Inside the export default function, we remove the dummy data and return the list of movies that we poll from the database. We also need to tell Apollo which query should be sent to the API, and we pass the GET_MOVIES query that we defined earlier.

When we refresh the browser, we can see the whole list of movies from our database:

Yay!

Add movie

So far, when we submit our form, nothing happens. We now want to be able to add movies over our form. For this, we need some changes in our AddMovie.vue file:

Again, inside the <script> tag, we need to import GraphQL. Also, we need to import the InMemoryCache. We’ll see why in just a bit.

In lines 17–39, we define our mutation to add movies to our database. First, we define the parameters that are passed. Second, we pass them as an object for a movie to be inserted. And third, we state the return value of our mutation which is, in our case the id of the movie that we just created.

The most substantial change inside the export default function is reflected in lines 52–67 where define what happens when the submit button is clicked. First, we need to prevent the default behaviour of a form being submitted when clicking on the button. Then, we define the data that is passed to the mutation. Next, we call our mutation on the $apollo instance and we pass the variables for the object creation. In the end, we need to refresh the movies list, because we don’t want to reload the browser for the newly added movie to appear in the list. For this, we need our cache. Because we ran the query to list movies before, we can just refetch it from the cache.

What now?

Good job! We now created a small Vue app and connected it to our GraphQL API. This was quite easy, wasn’t it? But this is just the beginning! There are a lot more features that can be added to our app. For example updating and deleting movies. Or displaying the characters and their corresponding actors for each movie. Check out the Hasura documentation. You can find everything that you need to extend this app.

Join the community

Hasura is being used by a growing number of developers. Join the friendly community and keep up with updates.

If you want to start building your own projects with Hasura, you can join their discord channel here. There is already a pretty large community and you will get help very quickly.

🐦 Twitter

⭐️ Github

--

--

Marion Schleifer

I'm obsessed with everything productivity and self improvement and I have a deep passion for helping others become more productive and happy.