in vanillaJS we are doing something like that to ajax call :
var request = new XMLHttpRequest();
request.open('GET','file.json',true);
request.onload = function (){
if(this.status >= 200 && this.status<400){
var data = JSON.parse(this.response);
console.log(data);
}
else{console.log("Error !");
}
request.send();
Now if we do this with arrow Functions it won't work because of this keyword.
Is there anyway to solve this problem and use it with arrow function or should I just stick with old way?
In short, there is no an "ES6 equivalent" for XMLHttpRequest (not even fetch) simply because none of them is an ECMAScript feature but part of the Web platform API defined by WHATWG and W3C.
However, to rewrite your code in a more "modern" way, using some ES6 features, you can procede as follows:
const request = new XMLHttpRequest();
request.addEventListener('load', (e) => {
// YOU COULD ALSO ACCESS request AS e.target HERE.
if (request.status >= 200 && request.status < 400) {
const data = JSON.parse(request.response);
console.log(data);
} else {
console.log('ERROR');
}
});
request.open('GET', 'file.json');
request.send();
Essentially we are using addEventListener API (which is still not an ES feature, but the latest specification to handle events in browsers). Then we are using const and an arrow function as handler which are ES6 features.
You don't need to use this as you can access your request through the event object or leveraging the reference stored in request variable.