I am reading the air-bnb javascript style guide and it says this should not be done:
23.5 Don’t save references to this. Use arrow functions or Function#bind.
// bad
function foo() {
const self = this;
return function () {
console.log(self);
};
}
// bad
function foo() {
const that = this;
return function () {
console.log(that);
};
}
// good
function foo() {
return () => {
console.log(this);
};
}
I already did some research and found two answers here in stackoverflow but the accepted answer in one of them is that this cannot be circumvented:
and the other one suggests using bind, but it suggested using a generator function.
Nested reference to `this` in ES6 classes
I am building a ReactJS app and I need to access setState from within a firebase Promise.
saveSessionToDB = () => {
const that = this;
db.collection("sessions")
.add({
props: MyProps
})
.then(function(docRef) {
console.log("Session written with ID: ", docRef.id);
that.setState({ sessionID: docRef.id });
})
.catch(function(error) {
console.error("Error adding document: ", error);
that.setState({ sessionError: error });
});
}
I tried
const {setState} = this;
and then
setState({sessionID:docRef.id});
but I get an error.
I tried binding the saveSessionToDB in the constructor to no avail, even if it's an arrow function.
Is there another way of doing this or should I just accept that sometimes I will have to still write const that = this?