shaan
shaan

Reputation: 524

wrapper function for axios

How to make a wrapper function for axios

I want to return axios from a function so that if my project switch to another fetch api it can easily done

I'm doing something like this

 import axios from 'axios'
export function apiCall(){
    axios.defaults.headers.common = {
    "X-Requested-With": "XMLHttpRequest",
    "X-CSRFToken": "example-of-custom-header"
    };
    return axios

 }

and in all actions i'm using something this

import apiCall from './somepath

function fetchContent(){
  return apiCall.get('http://localhost:3003/')
}

but I'm getting TypeError: _ApiCall__WEBPACK_IMPORTED_MODULE_3__.default.get is not a function

Upvotes: 2

Views: 3160

Answers (3)

apokryfos
apokryfos

Reputation: 40673

There's 2 things wrong with this code.

  1. It should be apicCall().get since apiCall is a function.
  2. Since you're using a non-default export you should use import {apiCall} from './somepath'

However here's how I suggest you do this:

import axios from 'axios';

axios.defaults.headers.common = {
    "X-Requested-With": "XMLHttpRequest",
    "X-CSRFToken": "example-of-custom-header"
};
export default axios;

This way you can do:

import axios from './somepath'

and then use the axios api as normal since that would be the same object.

Upvotes: 1

Dacre Denny
Dacre Denny

Reputation: 30360

In order to use the axios wrapper module as you've defined it, you'll need to invoke apiCall as a function like so:

import apiCall from './somepath

function fetchContent(){
  /* Add () after apiCall */
  return apiCall().get('http://localhost:3003/')
}

Upvotes: 1

Blundering Philosopher
Blundering Philosopher

Reputation: 6805

Try return apiCall().get('...') - emphasis on the extra parenthesis after apiCall()

Upvotes: 1

Related Questions