Value isn't replace and function return 0. How to fix it? (react-native 0.30, IOS 10.0 Simulator)
export function getCategoryList() {
var xhr = new XMLHttpRequest();
jsonResponse = null;
xhr.onreadystatechange = (e) => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
jsonResponse = JSON.parse(xhr.responseText);
} else {
console.warn('request_error');
}
};
xhr.open('GET', 'https://httpbin.org/user-agent');
xhr.send();
return jsonResponse;
}
You can't return the value like that.
I would suggest going with either callbacks or promises:
Callback:
function getCategoryList(callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = (e) => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
callback(JSON.parse(xhr.responseText));
} else {
console.warn('request_error');
}
};
xhr.open('GET', 'https://httpbin.org/user-agent');
xhr.send();
}
getCategoryList(data => console.log("The data is:", data));
Promises:
function getCategoryList() {
var xhr = new XMLHttpRequest();
return new Promise((resolve, reject) => {
xhr.onreadystatechange = (e) => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
resolve(JSON.parse(xhr.responseText));
} else {
console.warn('request_error');
}
};
xhr.open('GET', 'https://httpbin.org/user-agent');
xhr.send();
});
}
getCategoryList().then(res => console.log("The result is", res));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With