Last active
June 24, 2022 12:36
-
-
Save bessfernandez/4ead80f8f1b7e6f2db8c799bbc849794 to your computer and use it in GitHub Desktop.
A lightweight wrapper around axios with TS and async/await
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An axios wrapper using async/await and TS. Had a hard time finding any TS/async examples so hopefully this is helpful for folks!