Hi I was under the impression that if you use a arrow function, this refers to the enclosing scope as explained on the following link
https://www.sitepoint.com/bind-javascripts-this-keyword-react/:
- ES2015 Arrows
The ES2015 specification introduces the arrow function syntax for writing function expressions. As well as being terser than regular function expressions, they can also have implicit return and most importantly, they always use the value of this from the enclosing scope.
In the example below this
does not refer the the enclosing scope rather refers to the global scope.
addMeasurement(username,jsonObject){
...
return fetch(measurementURL,
{
method: 'PATCH',
body: jsonStringify
}).then( (res) => {
// this below refers to the global context.
//Instead of the current instance and hence is undefined
this.addMeasurementToAudit(username,jsonObject)
res.json()
});
}
Without arrow and explicitly binding this,works as expected:
addMeasurement(username,jsonObject){
...
return fetch(measurementURL,
{
method: 'PATCH',
body: jsonStringify
}).then( function success(res) {
//this refers to the enclosing instance and works as expected
this.addMeasurementToAudit(username,jsonObject)
res.json()
}.bind(this));
},