Programming

Consuming Axios in a Vue + Vuex project

This tutorial focus will show you how to assimilate Axios into your tool belt for use in future projects to help save you time and headache.

Prereqs:

  • Basic knowledge of
    • Vue.Js
    • Vuex
    • Axios
  • A preexisting Vuejs app with Vuex

What are we doing and why?

We are taking the Axios plugin for Vuejs and baking it into our own custom GET, POST, PUT and DELETE functions for future projects in a scalable, reusable manner, that will help stop some bad smells from appearing in your code.

Getting Started

Make a new file called “CRUD.js” This is where we will store all of our CRUD functions. let’s create a basic “GET” wrapper for Axios with some minimal error handling.

import axios from "axios"

const GetFunction = async function(route,params,headers)
{
    try
    {
        var results = await axios.get(route,{params,headers});
        return results.data;    
    }
    catch(error)
    {
        return error.response.data;
    }
}
export const Get = GetFunction;

Doing this alone only gives us the benefit of our own custom error handling. Which is nice but we can do much better. In the app where this solution was ultimately handled, the headers from the website did not change between requests, neither did the route. All we have to do to exploit this is add a few lines to our code so we may remove a few arguments from this function call

import axios from "axios"
import store from '@/store/store'

const GetFunction = async function(params)
{
    var address = store.state.address; 
    var headers = store.state.headers;
    try
    {
        var results = await axios.get(address,{params,headers});
        return results.data;    
    }
    catch(error)
    {
        return error.response.data;
    }
    
}

But why?

Basically this eliminates some headache for us down the line. By referring to our state we can refer to our API backend and our token simply by calling our “Get” export from our module. In the event that our API’s address changes, such as when we have a different IP/address from development to deployment, we don’t need to change every single Axios call in our project. Simply change what our state for what the address is, and then we can move on to deployment with a great deal less of worry on our shoulders.

Abe is a full-stack MEVN developer, who enjoys classical fencing with French Foil and German longsword. His interests also include photography, boxing, and Scotch whisky.

Leave a Reply

Your email address will not be published. Required fields are marked *