Convenience methods for Axios

Short snippet on adding convenience methods to the Axios HTTP library.

You may have already seen the $get, $post etc. convenience methods for Axios in a Nuxt project.

Before

const {data} = await axios.get('/cities')
this.cities = data

// or...
this.cities = (await axios.get('/cities')).data

As you can see, both ways aren't too fancy. Fortunately, it's pretty easy to add the convenience methods to Axios outside Nuxt.

After

this.cities = await axios.$get('/cities')

Much cleaner, right? Let's see how to set this up.

Setup

Create a new file called axios.js in your project. You might already have a file where you set your global Axios configuration.

axios.js
import {default as BaseAxios} from 'axios'

const axios = BaseAxios.create({
  baseURL: '/api/v1',
})

for (const method of ['request', 'delete', 'get', 'head', 'options', 'post', 'put', 'patch']) {
  axios['$' + method] = function () {
    return this[method]
      .apply(this, arguments)
      .then(res => res && res.data)
  }
}

export {axios}

Now you can use your new convenience methods in your code by importing your custom Axios instance:

import {axios} from './path/to/axios.js'

const updateCities = async () => {
  this.cities = await axios.$get('/cities')
}

How does it work

In the for-loop, we create a new method for each HTTP verb (get, post etc.) prepended with a $. These methods usually return a Promise resolving to the response object, that has our data. Since it is a Promise, it is possible to chain another .then(...) call to it and return the data object we want.

See also

Timo's Blog