Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

axios GET request function export/ import in react

Tags:

reactjs

axios

How do I export axios get request from separate .js file so I can use it in my main.js by importing i.e:

import { getNewQuote }  from './api'

class App extends Component {

  constructor () {
    super();
    this.state = {
      quote: []
    }
    this.handleNewQuote = this.handleNewQuote.bind(this);
  }
  componentDidMount() {
    getNewQuote();
  }

  handleNewQuote() {
    getNewQuote();
  }
   ...

My api.js looks like this:

export function getNewQuote(){
    axios.defaults.baseURL = 'https://andruxnet-random-famous-quotes.p.mashape.com';
    axios.defaults.headers.common['X-Mashape-Key'] = "MY-API-KEY";
    axios.get('/?cat=famous&count=1')
      .then(res => {
        this.setState({ quote: res.data })
      })
      .catch(error => {
        console.log(error)
      })
}

With this setup I'm getting an error in console:

TypeError: Cannot read property 'setState' of undefined at api.js:8 at

I assume the issue is with:

axios getNewQuote export or getNewQuote call in componentDidMount

Any help?

like image 518
karolis2017 Avatar asked May 06 '26 15:05

karolis2017


2 Answers

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)
  }
like image 51
Shubham Khatri Avatar answered May 09 '26 07:05

Shubham Khatri


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
}
like image 25
prabhatojha Avatar answered May 09 '26 06:05

prabhatojha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!