I'm new to react native and javascript. I've come from java and android dev. I'm looking to call a function within a const, but I just get a load of errors no matter what way I try it.
I'm getting the error :
this.collectionUpdate is not a function
MainScreen:
onCollectionUpdate = (doc) => {
const items = [];
doc.forEach((doc)=> {
console.log("doc received");
const {Name, imageDownloadUrl,Location} = doc.data();
items.push({
key: doc.id,
doc, //DocumentSnapshot
Name,
imageDownloadUrl,
Location,
});
});
this.setState({
items,
loading: false,
});
}
componentDidMount() {
const geoQuery = geoFirestore.query({
center: new firebase.firestore.GeoPoint(10.38, 2.41),
radius: 10.5
});
const onReadyRegistration = geoQuery.on('ready', () => {
console.log('GeoFirestoreQuery has loaded and fired all other events for initial data');
});
const onKeyEnteredRegistration = geoQuery.on('key_entered', function(key, doc, distance) {
console.log(key + ' entered query at ' + doc.coordinates.latitude
+ ',' + doc.Name
+ ',' + doc.coordinates.longitude
+ ' (' + distance + ' km from center)')
this.onCollectionUpdate(doc)
});
this.onCollectionUpdate = this.onCollectionUpdate.bind(this);
}
I know this is probably not working for me as I don't know enough in javascript to understand what I'm doing wrong but, I will start doing courses in Javascript soon to get a better understanding. But I would be very appreciative for anyone who could show me where I'm going wrong. I feel it's because I'm trying to call a function inside a const?
It's not about the const
, it's about the function
. Functions written with the keyword function
create a new scope for this
. When you use this
inside a function
, you're looking at a different this
from that outside of it.
geoQuery.on('key_entered', function(key, doc, distance) {
this.onCollectionUpdate(doc) // wrong "this"
})
One easy way to solve it is to just use a =>
function here:
geoQuery.on('key_entered', (key, doc, distance) => {
this.onCollectionUpdate(doc) // correct "this"
})