Skip to content

Instantly share code, notes, and snippets.

@roybarber
Created December 17, 2021 15:32
Show Gist options
  • Save roybarber/912699a69233390555f9507159f49e1b to your computer and use it in GitHub Desktop.
Save roybarber/912699a69233390555f9507159f49e1b to your computer and use it in GitHub Desktop.
Reusable ES6 Javascript API module using Axios - Promise
//////////////////////////////////////
// Generic service like function for
// Api requests using axios
// @param {String} url - api url
// @param {String} method - E.g POST, GET
// @param {Body} body - form body if needed
// @returns {Promise} data
//////////////////////////////////////
export const makeRequest = (url, method, body) => {
url = encodeURI(url)
return new Promise((resolve, reject) => {
const headers = {
"content-type": "application/json" // Add what you need
};
axios({
method: method,
url: url,
headers: headers,
data: JSON.stringify(body)
})
.then(response => resolve(response))
.catch(function (error) {
console.error(error)// Handle your error here or handle when you use the function
return reject(error);
});
});
};
// Usage:
// import { makeRequest } from "./makeRequest";
// make a reusable function like:
// const getProductPrice = (prop1, prop2) => {
// const url = `/endpoint?prop1=${prop1}&prop2=${prop2}`;
// return makeRequest(url, 'POST');
// };
// And do what you need with the promise...
// getProductPrice(prop1, prop2)
// .then(({data}) => {
// // do stuff with the data from the response (response.data)
// console.log({data})
// }).catch(error => {
// // we dont need to log the error as the makeRequest has already handled it, but if you need to reset state or remove anything do it here
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment