Skip to content

Instantly share code, notes, and snippets.

@antishok
Created October 18, 2019 22:07
Show Gist options
  • Save antishok/d9535facf5539b84169310aea33c6216 to your computer and use it in GitHub Desktop.
Save antishok/d9535facf5539b84169310aea33c6216 to your computer and use it in GitHub Desktop.
react-native fetch example
const config = require('../config');
async function ajax(path, data, {timeout} = {}) {
const opts = {
method: data ? 'POST' : 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'same-origin'
};
if (data) {
opts.body = JSON.stringify(data);
}
let fetchPromise = fetch(`${config.serverUrl}${path}`, opts);
let response = await (timeout ? timeoutPromise(timeout, fetchPromise) : fetchPromise);
if (!response.ok) {
let msg = `Request failed. Error code: ${response.status}`;
if (response.status === 400) {
try { msg = (await response.json()).error; }
catch (err) { msg = await response.text(); }
}
else if (response.status === 403) { msg = 'Permission denied'; }
const err = new Error(msg);
err.status = response.status;
throw err;
}
response = await response.json();
return response;
}
module.exports = ajax;
function timeoutPromise(ms, promise) {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("timeout")), ms);
promise.then(resolve, reject);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment