Skip to content

Instantly share code, notes, and snippets.

@iinsta
Last active December 4, 2017 21:28
Show Gist options
  • Save iinsta/86b6b1abbb2e7473229fd7b01092343d to your computer and use it in GitHub Desktop.
Save iinsta/86b6b1abbb2e7473229fd7b01092343d to your computer and use it in GitHub Desktop.
No fetch :) just XHR, because we can abort the request now!
/*
* usage
*
* componentDidMount() {
* likefetch('www.example.com/api/', {method: 'post', body: JSON.stringify({data: 123})}, c => this.xhr = c)
* }
* componentWillUnmount() {
* this.xhr && this.xhr.abort()
* }
*
*/
function likefetch(url, options, cb) {
options = options || {};
return new Promise( (resolve, reject) => {
let request = new XMLHttpRequest();
request.open(options.method || 'get', url);
for (let i in options.headers) {
request.setRequestHeader(i, options.headers[i]);
}
request.withCredentials = options.credentials=='include';
request.onload = () => {
resolve(response());
};
request.onerror = reject;
request.send(options.body);
typeof cb === 'function' && cb(request);
function response() {
let keys = [],
all = [],
headers = {},
header;
request.getAllResponseHeaders().replace(/^(.*?):\s*([\s\S]*?)$/gm, (m, key, value) => {
keys.push(key = key.toLowerCase());
all.push([key, value]);
header = headers[key];
headers[key] = header ? `${header},${value}` : value;
});
return {
ok: (request.status/100|0) == 2, // 200-299
status: request.status,
statusText: request.statusText,
url: request.responseURL,
clone: response,
text: () => Promise.resolve(request.responseText),
json: () => Promise.resolve(request.responseText).then(JSON.parse),
blob: () => Promise.resolve(new Blob([request.response])),
headers: {
keys: () => keys,
entries: () => all,
get: n => headers[n.toLowerCase()],
has: n => n.toLowerCase() in headers
}
};
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment