Skip to content

Instantly share code, notes, and snippets.

@thekingofbandit
Forked from sheharyarn/request.js
Created July 4, 2020 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thekingofbandit/839e3f7c7f4eb3db4bc0560c9f6c4928 to your computer and use it in GitHub Desktop.
Save thekingofbandit/839e3f7c7f4eb3db4bc0560c9f6c4928 to your computer and use it in GitHub Desktop.
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.

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...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment