Tips for fixing the error message "unable to access property 'property-name' of null"

I need assistance with retrieving data from a firebase database and storing it in an array using typescript. Below is the code snippet I am working with:

export class ViewUserPage {
  public list = [];
  public ref = firebase.database().ref();
  public usersRef = this.ref.child('users');

  constructor(public navCtrl: NavController, public navParams: NavParams) {}
  
  ionViewDidLoad(){
  
  this.usersRef.orderByChild('tag').equalTo('staff').on('child_added',function(snap){
    this.list.push(snap.val());console.log(snap.val());
    });

}

   

}

The issue I'm encountering is that I keep getting this error message "Cannot read property 'list' of null". It seems to be happening within the

this.usersRef.orderByChild('tag').equalTo('staff').on('child_added',function(snap){
    this.list.push(snap.val());console.log(snap.val());

part of the code. The complete error reads as follows:

ERROR TypeError: Cannot read property 'list' of null
    at main.js:59030
    at main.js:30999
    at fc (main.js:30861)
    at bf (main.js:30926)
    at cf (main.js:30925)
    at Qg.g.Gb (main.js:31016)
    at Ag.g.wd (main.js:30980)
    at og.wd (main.js:30970)
    at Yf.Xf (main.js:30968)
    at ag (main.js:30952)
defaultErrorLogger @ main.js:1436 

Any suggestions on how to address this issue would be greatly appreciated! Thank you!

Answer №1

Your current use of the function keyword is creating a new scope and altering the value of this. It's recommended to switch to fat arrow functions instead, as they do not affect the value of this. However, based on your comments, it appears that firebase may bind a different value for this, so storing the value of this in another variable like shown below would be necessary:

let that = this;
this.usersRef.orderByChild('tag').equalTo('staff').on('child_added', (snap) => {
    that.list.push(snap.val());
    console.log(snap.val());
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to authenticate with Next.js using JWT in a middleware is proving to be unsuccessful

Currently, I am authenticating the user in each API call. To streamline this process and authenticate the user only once, I decided to implement a middleware. I created a file named _middleware.ts within the /pages/api directory and followed the same appr ...

Ensure that the user's browser cache is cleared after deploying a new version on Firebase hosting

Utilizing create-react-app for my front end scripts and firebase hosting for deployment has been smooth overall. However, I've encountered an issue where updates to CSS and HTML files don't always reflect on the domain until I manually clear the ...

"Discover the step-by-step process of building a vue.js3 application with typescript, vue-router, and vuex without relying on

I have been assigned the task of developing a Vue3 application with TypeScript support using Vuex for state management and vue-router for basic routing. However, I am not allowed to use vue-cli for this project. Here is my current code: <head> & ...

Is it possible for a voiceover artist to initiate API requests?

As I work on the registration feature of my application, I am faced with the requirement that email addresses must be unique in the database. Since I am responsible for the front-end development, I am considering creating a Value Object (VO) that can make ...

Encountering a challenge with triggering a dialog box from an onClick event on a pie chart in Angular 8 when utilizing chart.js

I am currently using a chart.js pie chart to showcase some data. I have managed to display the required information in an alert box when a slice of the pie is clicked. However, I am now looking for a way to present this data in a dialog box instead. &a ...

Tips for testing an Angular Service that utilizes AngularFireDatabase by utilizing Jasmine Spy/Mock

I am currently testing my data service, and while I can successfully test it using real services like AngularFireDatabase, I am facing issues with getting the mocked version to work for testing purposes. The DataStorage class in use is designed to combine ...

What is the significance of the message "JavaScript files do not have any valid rules specified"?

I am working on a React - Typescript project that was created using the following command: create-react-app my-app --scripts-version=react-scripts-ts While it compiles without any issues, I keep receiving a message or warning that says: No valid rules h ...

Using style binding and ngStyle doesn't appear to be effective for setting a background image within a DIV element in Angular5

After facing difficulties in customizing the spacing of Angular material cards, I decided to create my own cards. However, during this process, I encountered an issue where I needed to set an image as a background inside a div. Despite trying various CSS ...

What is the best way to develop an Angular library with components in version 8 that can be seamlessly integrated into upcoming Angular versions such as 12, 13, and 14

Do I need to implement a new technique or setup in order to understand this? Can we use Angular elements as the only solution, or are there alternative approaches available? ...

The incorrect child output is causing the observable to trigger erroneously, resulting in the observable receiving inaccurate

For quite some time now, I've been struggling to identify the issue in my code. The scenario is that I have a child component acting as a modal, which includes a search bar. When the user interacts with the search bar, it triggers an event to the pare ...

Tips for testing an Express HTTP cloud function with various endpoints for posting, updating, and deleting data in Firestore

Is there a way to write unit tests for express http cloud functions like the one below? I've searched everywhere for examples, but I can't seem to find any information on writing tests for http cloud functions that have multiple REST endpoints ( ...

Turn off browser image caching

In order to provide users with fresh weather updates, my Earth weather web application receives new weather maps every six hours as images. I want to prevent the browser from caching these images to ensure that the user always sees the most current data, r ...

Encountered a problem during the installation of firebase @angular/fire

I've been developing an Angular chat application and ran into some issues when trying to install Firebase using the command "npm install --save firebase @angular/fire". The installation resulted in a series of errors, with the main problem appearing t ...

Angular 6 Integration: Configuring CORS and JWT in Spring Boot

While working on my Spring Boot app with JWT, I encountered a CORS error when attempting to login from the Angular 6 client. Access to XMLHttpRequest at 'http://localhost:8082/login' from origin 'http://localhost:4200' has been blocked ...

Is it possible to locate a Typescript class only when there are no references to its properties?

Currently, I am utilizing TypeScript 2.0 within VSCode and although the highlighted errors are being confirmed by the TypeScript compiler, they all point to a module that I am importing: import * as els from 'elasticsearch'; The module elastics ...

I am interested in deleting an element from Firebase using JavaScript

I'm struggling to grasp the concept of deleting an item from my Firebase database. I have successfully created a function (saveEmployee) to add items, but removing them is where I hit a roadblock. HTML <tbody ng-repeat="employee in employees"> ...

What are some techniques for breaking down or streamlining typescript code structures?

Within my TypeScript class, I have a skip function. In the interface, I've specified that the data is coming from the backend. Now, on the frontend, I want to be able to rename the backend variables as demonstrated below. There are multiple variables ...

detect the dismissal event in the modal controller from the main component

Within my MainPage, I invoke the create function in the ModalController, which displays the ModalPage. Upon clicking cancel, the dismiss function is called and we are returned to the MainPage. The process functions as expected. @Component({ selector: &a ...

Child component received an incorrect input value

Utilizing both the "YearComponent" and "StatPeriod" components has presented some challenges for me. Within my YearComponent, I invoke StatPeriod as follows: <app-save-stat-period [dateBegin]="dateBegin" [dateEnd]="dateEnd" byMonth bestNAverage></ ...

What is the process of converting a union type into a union of arrays in TypeScript?

I have a Foo type that consists of multiple types For example: type Foo = string | number I need to receive this type and convert it into an array of the individual types within the union type TransformedFoo = ToUnionOfArray<Foo> // => string[] ...