Skip to content

Instantly share code, notes, and snippets.

@garikaijenje
Last active April 12, 2021 07:14
Show Gist options
  • Save garikaijenje/d16d1f6fecbc002a87b898af5ce5b99a to your computer and use it in GitHub Desktop.
Save garikaijenje/d16d1f6fecbc002a87b898af5ce5b99a to your computer and use it in GitHub Desktop.
The last React API Call function you'll ever need
import axios from 'axios';

const API = axios.create({ baseURL: "YOUR_API_BASE_URL_HERE", responseType: 'json'});

const setHeaders = (token, contentType) => {
    let headers = {
        Accept: "application/json"
    }
    if (contentType) headers["Content-Type"] = contentType;
    if (token) headers.Authorization = `Bearer ${token}`;

    return headers;
}

export const ApiRequest = {
    get: ({endpoint, token = null, contentType = null, success, failure}) => {
        return API.get(endpoint, setHeaders(token, contentType))
        .then(async (response) => await success(response))
        .catch((error) => failure(error));
    },
    post: ({endpoint, token = null, contentType = null, data, success, failure}) => {
        return API.post(endpoint, data, setHeaders(token, contentType))
        .then(async (response) => await success(response))
        .catch((error) => failure(error));
    },
    delete: ({endpoint, token = null, contentType = null, success, failure}) => {
        return API.delete(endpoint, setHeaders(token, contentType))
        .then(async (response) => await success(response))
        .catch((error) => failure(error));
    }
};

Here's an example implementation

ApiRequest.post({
  endpoint: 'auth/login',
  // token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9',
  // contentType: 'application/json',
  data: {},
  success: (response) => { },
  failure: (error) => { }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment