Reader small image

You're reading from  Front-End Development Projects with Vue.js

Product typeBook
Published inNov 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838984823
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
Raymond Camden
Raymond Camden
author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

Hugo Di Francesco
Hugo Di Francesco
author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

Clifford Gurney
Clifford Gurney
author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

Philip Kirkbride
Philip Kirkbride
author image
Philip Kirkbride

Philip Kirkbride has over 5 years of experience with JavaScript and is based in Montreal. He graduated from a technical college in 2011 and since then he has been working with web technologies in various roles.
Read more about Philip Kirkbride

Maya Shavin
Maya Shavin
author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin

View More author details
Right arrow

10. Working with Vuex – Fetching Remote Data

Overview

In this chapter, you will learn how to work with remote APIs using the Axios library. You will make network calls and store results using Vuex. You will also see an example of how to store authentication tokens with Vuex and use it for further API calls.

By the end of this chapter, you will have a good idea of how Vuex can help abstract and create a wrapper for remote APIs, and ease their integration into a Vue application. This abstraction makes it easier to migrate to other APIs in the future, ensuring that the rest of your applications continue to work properly.

Introduction

In Chapter 9, Working with Vuex – State, Getters, Actions, and Mutations, you were introduced to Vuex and saw multiple examples of how to work with it to both read data from and write data to a store. We saw how multiple components could work with the store and all be kept in sync with little to no work at our end. In this chapter, we are going to expand our Vuex usage by integrating it with remote data by using Axios, a popular open source library that makes it easy to use network resources. Let's start off with a deeper look at Axios.

Axios (https://github.com/axios/axios) is a JavaScript library with both Node and browser support. It has a Promise-based API, which means you can use async and await if you wish. Other features include supporting default parameters (handy for APIs that require a key for every call) and the ability to transform your input and output data. We will not be covering every use case in this chapter, but you will get a good idea...

Installation of Axios

Much like Vuex, you have multiple ways of including Axios in your project. The simplest is pasting in a <script> tag pointing to the Content Delivery Network (CDN) for the library:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

The other option is to use the Node Package Manager, npm. Within an existing Vue application, you can install Axios as follows:

npm install axios

Once you have done this, your Vue components can then import the library as follows:

import axios from 'axios';

How you use Axios will depend on the API you are interacting with. Here is a simple example of hitting an imaginary API:

axios.get('https://www.raymondcamden.com/api/cats')
.then(res => {
  this.cats = res.data.results;
})
.catch(error => {
  console.error(error);
});

In the preceding example, we are performing a GET request (GET is the default) against an imaginary...

Using Defaults with Axios

While the code in Exercise 10.01, Using Axios to Load Data from an API works well, let's consider a slightly more advanced example. One of the features of Axios is the ability to set up defaults that are used in future calls. If you look at the two calls made in the preceding code, you can see they are similar. You can update the created method to make use of this:

created() {
  const api = axios.create({
    baseURL:'https://swapi.dev/api/',
    transformResponse(data) {
      data = JSON.parse(data);
      return data.results;
    }
  });
  api.get('films')
  .then(res => this.films = res.data);
  api.get('starships')
  .then(res => this.ships = res.data);
}

In this updated version, we switch to an instance of Axios. A default baseURL...

Using Axios with Vuex

Now that you have seen the basics of working with Axios, it is time to consider how you could use it with Vuex. One way to do this simply is to just use Vuex to handle wrapping calls to the API, using Axios to perform the HTTP calls.

Exercise 10.02: Working with Axios in Vuex

We are going to take the previous functionality (loading the films and ships arrays) and rebuild it within the context of a Vuex store instead. As before, you will need to use the CLI to scaffold a new application and ensure you ask for Vuex to be included. When the CLI is done, you can then use the npm command to add Axios as well.

This exercise will be pretty much like the first application that we built in Exercise 10.01, Using Axios to Load Data from an API, but with some slight differences. Let's look at the UI first. On the initial load, both Films and Ships are empty:

Figure 10.2: Initial application UI

Notice that the Films portion has a...

Summary

In this chapter, you learned a pretty important use case for Vuex—working with remote APIs. Remote APIs can provide an incredible amount of additional functionality to your applications, sometimes for little to no additional cost to the developer. You saw how to use Axios to make network calls easier and how to combine that with the state management features of Vuex. Finally, you put it together with Vue Router to create a simple login/authorization demo.

In the next chapter, we are going to discuss how to build more complex Vuex stores using modules.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Front-End Development Projects with Vue.js
Published in: Nov 2020Publisher: PacktISBN-13: 9781838984823
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

author image
Philip Kirkbride

Philip Kirkbride has over 5 years of experience with JavaScript and is based in Montreal. He graduated from a technical college in 2011 and since then he has been working with web technologies in various roles.
Read more about Philip Kirkbride

author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin