question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using new keyword / extending axios object?

See original GitHub issue

I’m interesting in creating an API wrapper and extending from axios using es6 classes. How is this possible? Axios has a method .create() which allows you to generate a new axios object.

class Api extends Axios {
  constructor(...args){
    super(..args)
    this.defaults.baseURL = 'https://api.com'
  }
  cancelOrder (id) {
    return this.put(`/cancel/order/${id}`)
  }
}

I know I have access to this let instance = axios.create().

Any thoughts?

Attempt 1

import axios from 'axios'
const Axios = axios.create()

class Api extends Axios {
  constructor (...args) {
    super(...args)
    this.defaults.baseURL = 'https://api.com'
  }
  cancelOrder (id) {
    return this.put(`/cancel/order/${id}`)
  }
}

let api = new Api()

api.cancelOrder('hi')
  .then(console.log)
  .catch(console.log)

Attempt 2

import axios from 'axios'

class Axios {
  constructor () {
    return axios.create()
  }
}

class Api extends Axios {
  constructor () {
    super()
    this.defaults.baseURL = 'https://api.com'
  }
  cancelOrder (id) {
    return this.put(`/cancel/order/${id}`)
  }
}

let api = new Api()

console.log(api.__proto__)

api.cancelOrder('hi')
  .then(console.log)
  .catch(console.log)

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:1
  • Comments:15 (7 by maintainers)

github_iconTop GitHub Comments

12reactions
SavePointSamcommented, Jun 10, 2017

For anyone that ends up here in the future. If you’re just trying to define a way to get a new instance with application standard options, or wrap an axios instance in a custom es6 class. You just need to return the instance you define from the class constructor.

import axios from 'axios';

// add session token to all requests
const requestInterceptor = (config) => ({
  ...config,
  headers: {
    ...config.headers,
    'x-auth-token': localStorage.getItem('token'),
  },
});

class Client {
  constructor() {
    const options = {};
    const instance = axios.create(options);

    instance.interceptors.request.use(requestInterceptor);

    return instance;
  }
}

export default Client;
import Client from './Client';

const getUsers = () => (
  new Client().get('/api/users')
);
8reactions
yordiscommented, Jan 16, 2018

Just for a little feedback in about @SavePointSam comment

That is just a function call, you do not need to create a class for do what he is suggesting to do.

const Client = () => {
    const options = {};
    const instance = axios.create(options);

    instance.interceptors.request.use(requestInterceptor);

    return instance;
  }

const client = Client()

also in terms of readability I wouldn’t do it either. It is not a good practice to be returning different objects from the original object you are trying to create a from.

When I do new Client() I am expecting a instance of Client no AxiosInstance.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using es6 class to extend Axios - Stack Overflow
I do not believe that an instance object can be extended in es6. Your second attempt seems most viable, but if you want...
Read more >
How To Use Axios with React - DigitalOcean
In this article, you will see examples of how to use Axios to access the popular JSON Placeholder API within a React application....
Read more >
The New Keyword - Beginner JavaScript - Wes Bos
To reiterate, by using the new keyword in JavaScript, it creates a new object that is an instance of whatever function you have...
Read more >
The Power of Axios - Bits and Pieces
Axios is a powerful promise-based HTTP client used to make requests to external servers from the browser. If you are a front-end developer, ......
Read more >
Class is not a class. Extends doesn't Extend in JS - Medium
Since we did not use the new operator, the second console did not ... For languages that do not use the extends keyword...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found