Skip to content

Instantly share code, notes, and snippets.

@ownaginatious
Last active August 16, 2023 09:56
Show Gist options
  • Save ownaginatious/503a75a68a7bc376d11944950af855c7 to your computer and use it in GitHub Desktop.
Save ownaginatious/503a75a68a7bc376d11944950af855c7 to your computer and use it in GitHub Desktop.
React native XHR request
request = (opts) => {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
let url = opts.url;
let params = opts.query_params;
if (params && typeof params === 'object') {
params = Object.keys(params).map(function(key) {
return encodeURIComponent(key).replace(/%20/g, '+') +
'=' + encodeURIComponent(params[key]).replace(/%20/g, '+');
}).join('&');
url = url + '?' + params;
}
xhr.open(opts.method, url);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject({
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function() {
reject({
status: xhr.status,
statusText: xhr.statusText
});
};
if (opts.headers) {
Object.keys(opts.headers).forEach(function(key) {
xhr.setRequestHeader(key, opts.headers[key]);
});
}
if (opts.method.toUpperCase() == 'POST'){
xhr.send(opts.body);
} else {
xhr.send()
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment