Skip to content

Instantly share code, notes, and snippets.

@jhadev
Last active December 14, 2023 19:15
Show Gist options
  • Save jhadev/5a48b2061170bed111424d97e4564347 to your computer and use it in GitHub Desktop.
Save jhadev/5a48b2061170bed111424d97e4564347 to your computer and use it in GitHub Desktop.
reuseable-fetch.js
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