score:8

Accepted answer

you can return the promise from the axios request and then handle it in the calling function like

export function getnewquote(){
    axios.defaults.baseurl = 'https://andruxnet-random-famous-quotes.p.mashape.com';
    axios.defaults.headers.common['x-mashape-key'] = "my-api-key";
    return axios.get('/?cat=famous&count=1')
}

and using it like

componentdidmount() {
    getnewquote().then(res => {
        this.setstate({ quote: res.data })
      })
      .catch(error => {
        console.log(error)
      });
  }

  handlenewquote() {
    getnewquote().then(res => {
        this.setstate({ quote: res.data })
      })
      .catch(error => {
        console.log(error)
      });
  }

or call the getnewquote function using the javascript .call method and passing the reference of this to it like

 componentdidmount() {
    getnewquote.call(this)
  }

  handlenewquote() {
    getnewquote.call(this)
  }

score:3

the above answer is absolutely correct, but what i want to focus is writing dry code, so this is how i do it.

import axios from 'axios';
class baseservice {
  constructor() {
    this.baseurl = "/api";
  }

  getdata(path) {
    let url = `${this.baseurl}${path}`;
    return axios.get(`${url}`);
  }
}

export default (new baseservice()); // singleton object

this base service is now can be imported in other component or services.

import baseservice from './services/base.service.jsx';

class home extends react.component {
constructor(props) {
    super(props);

    this.state = {
        data: []
    }

}

componentdidmount() {
    let path = '/users';
    baseservice.getdata(path)
        .then(resp => {
            this.setstate({data: resp.data});
        }); // handle errors if needed
}

Related Query

More Query from same tag