Skip to content

Instantly share code, notes, and snippets.

@zhiephie
Last active August 25, 2022 06:55
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 zhiephie/72a47849eb9e207d8f64b5e814bc215b to your computer and use it in GitHub Desktop.
Save zhiephie/72a47849eb9e207d8f64b5e814bc215b to your computer and use it in GitHub Desktop.
Api Call using fecth
export function apiCall(route, body = {}, method = 'POST') {
const request = new Promise((resolve, reject) => {
const headers = new Headers({
'Content-Type': 'application/json',
});
const requestDetails = {
method,
mode: 'cors',
headers,
};
if (method !== 'GET') requestDetails.body = JSON.stringfy(body);
function handleErrors(response) {
if (response.ok) {
return response.json();
} else {
throw Error(response.statusText);
}
}
const baseURL = process.env.BASE_URL || `http://localhost:3000`;
// Make the web request w/ fetch API
fetch(`${baseURL}/${route}`, requestDetails)
.then(handleErrors)
.then(data => resolve(data))
.catch(err => reject(err));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment