Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Axios Request Wrapper for React (https://to.shyr.io/axios-requests)
/**
* Axios Request Wrapper
* ---------------------
*
* @author Sheharyar Naseer (@sheharyarn)
* @license MIT
*
*/
import axios from 'axios'
import constants from 'shared/constants'
/**
* Create an Axios Client with defaults
*/
const client = axios.create({
baseURL: constants.api.url
});
/**
* Request Wrapper with default success/error actions
*/
const request = function(options) {
const onSuccess = function(response) {
console.debug('Request Successful!', response);
return response.data;
}
const onError = function(error) {
console.error('Request Failed:', error.config);
if (error.response) {
// Request was made but server responded with something
// other than 2xx
console.error('Status:', error.response.status);
console.error('Data:', error.response.data);
console.error('Headers:', error.response.headers);
} else {
// Something else happened while setting up the request
// triggered the error
console.error('Error Message:', error.message);
}
return Promise.reject(error.response || error.message);
}
return client(options)
.then(onSuccess)
.catch(onError);
}
export default request;

Axios Request Wrapper

I love the 'services' architecture of making requests in Angular, and wrote this little wrapper (and instructions) for my React and other JS projects.

Blog Post

Simple Usage Example

request({
  method: 'get',
  url: '/path/'
}).then((resp) => {
  console.log(resp);
})

Proper Usage

Create a separate service for your API Calls:

// services/api/message.js

import request from 'shared/lib/request'

function get(id) {
  return request({
    url:    `/message/${id}`,
    method: 'GET'
  });
}

function create({subject, content}) {
  return request({
    url:    '/message/create',
    method: 'POST',
    data:   {
      subject,
      content
    }
  });
}

const MessageService = {
  get, create //, update, delete, etc. ...
}

export default MessageService;

Now call the methods from your module/view/component:

import React from 'react'
import MessageService from 'services/api/message'

class Message extends React.Component {
  handleSubmit() {
    const {subject, message} = this.state;
    
    MessageService
      .create({subject, message})
      .then((response) => {
        alert(`New Message with id ${response.id} created!`);
      });
  }
  
  // Other stuff...
}
@bsthomsen

This comment has been minimized.

Copy link

@bsthomsen bsthomsen commented Nov 26, 2017

Good stuff, how would you handle adding Authorization: Bearer ${token} on all requests if authenticated?

@jampack

This comment has been minimized.

Copy link

@jampack jampack commented Dec 17, 2017

@bsthomsen
set this parameter on Create method

const client = axios.create({
  baseURL: constants.api.url,
  auth: { Authorization: 'Bearer ' + {token}}
});
@philmetzger

This comment has been minimized.

Copy link

@philmetzger philmetzger commented Dec 20, 2017

I had an issue when I did this in getInitialProps of my NextJS app. I changed all the console.x to console.log and that fixed it.

@GazzaHazza

This comment has been minimized.

Copy link

@GazzaHazza GazzaHazza commented Dec 29, 2017

How would this work with async/await?

@dynnt27

This comment has been minimized.

Copy link

@dynnt27 dynnt27 commented Jan 10, 2018

Thanks for this. Helped me as a noob in wrapping my axios

@leocostaba

This comment has been minimized.

Copy link

@leocostaba leocostaba commented Jan 20, 2018

Perfect, I searched a lot the best way to wrapping my Axios Resquests. You solved it!

@TonyNikolov

This comment has been minimized.

Copy link

@TonyNikolov TonyNikolov commented Feb 7, 2018

This is exactly how code should be written, thank you for sharing this so i dont have to write it myself!

@jbesraa

This comment has been minimized.

Copy link

@jbesraa jbesraa commented Apr 27, 2018

@bsthomsen

const myFun = token => {
  return request({
    url: "/path/to",
    method: "GET",
    config: {
      Authorization: `Bearer ${token}`
    }
  });
};
@rmdJ

This comment has been minimized.

Copy link

@rmdJ rmdJ commented Nov 24, 2018

Hello, how would you mock your axios request for action (redux) tests?

@boyanenchev1

This comment has been minimized.

Copy link

@boyanenchev1 boyanenchev1 commented Dec 18, 2018

Hello, how would you mock your axios request for action (redux) tests?

@jmberon

This comment has been minimized.

Copy link

@jmberon jmberon commented Sep 4, 2019

👌

@Abubakr077

This comment has been minimized.

Copy link

@Abubakr077 Abubakr077 commented Oct 1, 2019

can we add polling functionality in this wrapper?

@maxwaiyaki

This comment has been minimized.

Copy link

@maxwaiyaki maxwaiyaki commented Mar 3, 2021

axios.interceptors.request.use(
async config => {
const token = await AsyncStorage.getItem('token')
if (token) {
config.headers.Authorization = "Bearer "+token
}
return config
},
error => {
return Promise.reject(error)
}
);

how to add this to the above wrapper???

Any progress on this??

@Ajmal0197

This comment has been minimized.

Copy link

@Ajmal0197 Ajmal0197 commented Mar 16, 2021

USING WRAPPER WITH REDUX SAGA:
//api call in saga

        let response1 = yield call(apiCall, "GET", serviceUrl.user)//Get request
        let response2 = yield call(apiCall, "POST", serviceUrl.user, {
            title: 'foo',
            body: 'bar',
            userId: 1,
        })  //post request
        console.log('loginGenobject', response1, response2)

//api call wrapper

import axios from 'axios'
import { serviceUrl } from '../constants/constants'
import AsyncStorage from '@react-native-async-storage/async-storage';

/**
 * Create an Axios Client with defaults
 */

const getToken = async () => await AsyncStorage.getItem("access-token")

const client = axios.create({
    baseURL: serviceUrl.baseURL,
    // auth: { Authorization: 'Bearer ' + { getToken } }
});

/**
* Request Wrapper with default success/error actions
*/
export const apiCall = function (method, route, body = null, token = null) {

    const onSuccess = function (response) {
        console.debug('Request Successful!', response);
        return response.data;
    }

    const onError = function (error) {
        console.error('Request Failed:', error.config);

        if (error.response) {
            // Request was made but server responded with something
            // other than 2xx
            console.error('Status:', error.response.status);
            console.error('Data:', error.response.data);
            console.error('Headers:', error.response.headers);

        } else {
            // Something else happened while setting up the request
            // triggered the error
            console.error('Error Message:', error.message);
        }

        return Promise.reject(error.response || error.message);
    }

    return client({
        method,
        url: route,
        data: body
    }).then(onSuccess)
        .catch(onError);
}


//USAGE:
// const myFun = token => {
//     return request({
//       url: "/path/to",
//       method: "GET",
//       config: {
//         Authorization: `Bearer ${token}`
//       }
//     });
//   };
// request({
//     method: 'get',
//     url: 'posts',
// }).then((resp) => {
//     console.log('resp', resp);
// })

// request({
//     method: 'POST',
//     url: 'posts',
//     data: {
//         title: 'foo',
//         body: 'bar',
//         userId: 1,
//     }
// }).then((resp) => {
//     console.log('resp', resp);
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment