Logan Saruwatari Logan Saruwatari - 1 month ago 7
Javascript Question

ES6: How to use, "this", with fetch?

I have read a decent amount of documentation on ES6 and what has changed with it. I am trying to embrace the new oop syntax with some of the new libraries like fetch. So here's the code I have:

apiCall(url, thisAlias=this){
fetch(url).then(function(response){
return response.json();
})
.then(function(respObj){
thisAlias.domUpdater(respObj);
});
}


This is in a base class that has an inherited class and will eventually have many inherited classes. The idea is to have a universal api call using fetch and I can change the domUpdater method per inherited class. I spent a lot of time getting this code to work, aliasing the this keyword so that it could be used within the fetch call. Is there a more elegant way to do this? I can't seem to pass this directly as an argument.

Answer

Using arrow functions which have lexical this will help you the most with this particular piece of code

apiCall (url) {
  fetch(url).then(
    response => response.json(),
  ).then(
    respObj => this.domUpdater(respObj)
  ).catch(
    err => console.error(err.message, err)
  )
}

Otherwise if you can use the newer async/await, you don't have to worry about this pointing to the wrong thing at all – even without arrow functions.

async apiCall (url) {
  try {
    let response = await fetch(url);
    this.domUpdater(response.json());
  }
  catch (err) {
    console.error(err.message, err);
  }
}
Comments