Last active
December 14, 2023 19:15
-
-
Save jhadev/5a48b2061170bed111424d97e4564347 to your computer and use it in GitHub Desktop.
reuseable-fetch.js
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
function client(endpoint, { body, ...customConfig } = {}) { | |
const headers = { 'Content-Type': 'application/json' }; | |
const config = { | |
method: body ? 'POST' : 'GET', | |
...customConfig, | |
headers: { | |
...headers, | |
...customConfig.headers, | |
}, | |
}; | |
if (body) { | |
config.body = JSON.stringify(body); | |
} | |
return window | |
.fetch(endpoint, config) | |
.then(async (response) => { | |
const data = await response.json(); | |
if (response.ok) { | |
return data; | |
} else { | |
return Promise.reject(data); | |
} | |
}); | |
} | |
export { client }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment