Last active
August 25, 2022 06:55
-
-
Save zhiephie/72a47849eb9e207d8f64b5e814bc215b to your computer and use it in GitHub Desktop.
Api Call using fecth
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
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