"Cannot set property of null" in Firebase


I’ve set up a simple system to favorite places. When a place isn’t added to a user’s favorites, they can add it to their favorites. Vice versa, they can remove a place when they’ve already added it to their favorites. This is solved by using simple *ngIf buttons and it works fine.

However, since the value of the boolean that manages the *ngIf buttons isn’t saved when a user leaves the page, it always defaults back to the default value (in this case false) when they leave the page.

I’m trying to change this by asking the Firebase database if the current place is already among their favorites (using exist()). If the place is already favorited, the boolean should be set to true, otherwise to false. This is the code I’m using:

firebase.database().ref('/userProfile/'  + firebase.auth().currentUser.uid + '/favorites/'+ this.lpName).on('value', 
    if (snapshot.exists()) {
      this.hearted = true;
   } else { 
     console.log("Doesn't exist")      
     this.hearted = false;

The console.logs will trigger correctly, so the code does seem to recognize whether a place already exists as a favorite or not. However, when I add the code to change the value of hearted, it always displays an “Cannot set property ‘hearted’ of null” error. I don’t understand why or when it’s trying to set the value of hearted to null, however. What am I doing wrong?


You should almost never type function.

Instead you should make use of fat arrows, so, change it from:

function(snapshot) {


(snapshot) => {

The short version of the why of this, is because this is a funny concept in JavaScript, which Typescript fixes with fat arrows.


Just fyi, the Firebase documentation uses code samples from ES5. So the code works, but is bad/outdated style. The OP probably tried to copy the Firebase docs. To the OP: @SigmundFroyd is right, but it means you need to learn Typescript and ES6, and then translate the Firebase docs into something better.

Also, you don’t post the code that’s causing the problem, so it’s impossible to answer your specific question.


Thank you, changing the code to the fat arrow style solved the issue. It’s now working as intended.