Skip to content

Instantly share code, notes, and snippets.

@bessfernandez
Last active June 24, 2022 12:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bessfernandez/4ead80f8f1b7e6f2db8c799bbc849794 to your computer and use it in GitHub Desktop.
Save bessfernandez/4ead80f8f1b7e6f2db8c799bbc849794 to your computer and use it in GitHub Desktop.
A lightweight wrapper around axios with TS and async/await
// A wrapper around axios with TS and async/await
// code below would be it's own .tsx file:
/* eslint-disable no-console */
import axios from 'axios';
const apiRoot = 'http://localhost:3000/';
/**
* Create an Axios Client with baseURL as default
*/
const client = axios.create({
baseURL: apiRoot,
});
/**
* A lightweight wrapper for axios - a Promise based HTTP client for the browser and node.js
* see https://github.com/axios/axios#request-config for config options
*/
const request = async (options: {}) => {
const onSuccess = (response: {}) => {
console.debug('Request successfull:', response);
return response;
};
const onError = (error: {
config: {};
response: { status: string; data: {}; headers: {} };
message: string;
}) => {
console.error('Request failed:', error.config);
if (error.response) {
console.error('Status:', error.response.status);
console.error('Data:', error.response.data);
console.error('Headers:', error.response.headers);
} else {
// log message if it wasn't based on the response
console.error('Error Message:', error.message);
}
return error.response || error.message;
};
const response = await client(options)
.then(onSuccess)
.catch(onError);
return response;
};
export default request;
// Separate implementation outside of the wrapper below
// Usage would be like this in your other tsx:
/**
* Get data from API via axios `post()
* @param url
*/
const postData = async (url: string): Promise<any> => {
const response = request({
url,
method: 'POST',
data: configSample,
headers: headersSample,
});
return response;
};
// kicked offlike so (used in my case with Redux)
const asyncResp: any = await postData('/api');
@bessfernandez
Copy link
Author

An axios wrapper using async/await and TS. Had a hard time finding any TS/async examples so hopefully this is helpful for folks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment