Skip to content

Instantly share code, notes, and snippets.

@rusrushal13
Created February 19, 2020 06:44
Show Gist options
  • Save rusrushal13/250877880e34b5c0cedf69e714d77a00 to your computer and use it in GitHub Desktop.
Save rusrushal13/250877880e34b5c0cedf69e714d77a00 to your computer and use it in GitHub Desktop.
export const checkStatus = response => {
if (
response.status >= 200 &&
response.status < 300
) {
return response;
}
return response.json().then(json => {
return Promise.reject({
status: response.status,
ok: false,
statusText: response.statusText,
body: json
});
});
};
export const parseJSON = response => {
return response.json();
};
export const parseHTML = response => {
return response.text();
};
const fetchData = async (url, options) => {
const headers = {
...options.headers,
// Authorization: token
};
options = {
...options,
headers: headers
};
return fetch(url, options)
.then(checkStatus)
.then(headers["accept"] && headers["accept"] === "text/html" ? parseHTML : parseJSON)
.then(data => data)
.catch(error => error);
};
export default fetchData;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment