The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered:

core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined
TypeError: Cannot set property 'userNm' of undefined

Below is the code snippet in TypeScript (ts):

userNm: string ='';

ngOnInit(){

   console.log("trying...");
   firebase.firestore().collection(`Students`)
   .where("authId", "==", this.userId) 
   .get()
   .then(querySnapshot => {
     querySnapshot.forEach(function(doc) {
         console.log(doc.data().Name); // OK RESULT IN CONSOLE.LOG, NAME IS String in db.
         this.userNm = doc.data().Name;  // ERROR HERE
         console.log(this.userNm)
         console.log(doc.id, " ===> ", doc.data());
     });
   });

Screenshot showing the error and database records:

https://i.sstatic.net/aqYWD.png

https://i.sstatic.net/MFRUR.png

Answer â„–1

This keyword within a JavaScript function() actually points to the specific function's scope. To access member variables, it is recommended to use the arrow function syntax. You may want to consider implementing the following approach:

firebase.firestore().collection(`Students`)
  .where("authId", "==", this.userId) 
  .get()
  .then(querySnapshot => {
    querySnapshot.forEach((doc) => {   // <-- Make use of arrow function at this point
      console.log(doc.data().Name);
      this.userNm = doc.data().Name;
      console.log(this.userNm)
      console.log(doc.id, " ===> ", doc.data());
    });
  });

Answer â„–2

querySnapshot.forEach(function(doc)
showcases the utilization of an anonymous function characterized by this. Try utilizing lambda instead. ..

querySnapshot.forEach((doc) =>{

querySnapshot.forEach((doc) =>{
         console.log(doc.data().Name); // Successfully logs the name stored as String in the database.
         this.userNm=doc.data().Name;  // An error occurs at this line
         console.log(this.userNm)
         console.log(doc.id, " ===> ", doc.data());
     });

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

Optimizing Angular: Configuring baseHref for assets during development with SSR

During production, we set the base href using the following command: ng build --base-href /app/ This configuration works smoothly as our assets are also accessible at /app/assets/, just as expected. However, I have been facing difficulties achieving the ...

Run code once the Firestore get method has completed its execution

Is it possible to execute code after the get method is finished in JavaScript, similar to how it can be done in Java (Android)? Below is an example of my code: mColRef.get().then(function(querySnapshot){ querySnapshot.forEach(function(doc) { ...

Using a Button component as a TableCell in a material-ui Table

Hey there! I'm looking for some assistance in adding buttons as TableRowColumns in the material-ui Table. I'm working on implementing an approval system to approve or reject user requests, and I thought presenting them in a tabular format would b ...

Ways to retrieve the current URL in Next.js without relying on window.location.href or React Router

Is there a way to fetch the current URL in Next.js without relying on window.location.href or React Router? const parse = require("url-parse"); parse("hostname", {}); console.log(parse.href); ...

Effective steps after Ajax request

Whenever a user clicks the "like" button, I perform a check in the database to see if they have already liked the photo. This check is done using ajax. If the photo has already been liked, the success message will indicate "already liked", otherwise it wi ...

Pressing the tab key while using Angular will halt any additional processes from running

I recently integrated a search bar into my Angular application. When I enter text in the input field, a customized dropdown menu appears below it. However, when I press the tab key, I expect the dropdown to close and for the focus to shift to the next inpu ...

Calculating the dot product of two arrays using JavaScript

let array1 = [2,4,6] let array2 = [3,3,3] let result = dotProduct(array1,array2) // should return 36 Can you suggest a streamlined approach to creating the dotProduct function without relying on external libraries? ...

Saving a boolean value and a number to Firestore in an Angular application

In my Angular 5 typescript project, I have a form with various input fields and selections. Here is how I am capturing the form values: let locked: boolean = (<HTMLInputElement>document.getElementById("locked")).value; let maxPlayers: number = (& ...

Encountering difficulties in populating mongoose document following a model query

Hi everyone, this is my first time posting on SO so I'm hoping for some positive outcomes. I've been using Mongoose in a current project without any issues until now. The problem arises when trying to populate object references after querying fo ...

An operator in rxjs that transforms an Observable of lists containing type X into an Observable of type X

Currently, I am facing a challenge while dealing with an API that is not very user-friendly using Angular HTTP and rxjs. My goal is to retrieve an Observable<List<Object>> from my service. Here's a snippet of the JSON output obtained from ...

Troubles with a Chrome Extension for JSON

I'm currently working on a project to develop a Google Chrome extension and I've encountered an obstacle. I'm experimenting with JSON data (with the intention of integrating it with an API in the future). I have a sample JSON file, successfu ...

What method is best for deleting an item from the database in HTML structure - POST, GET, or XHR action?

I have a webpage that displays content in a table format and allows users to delete a specific row by clicking on it. The structure of my rows is as follows: foreach ($rewards as $reward) { echo '<tr id="' . $reward[&apos ...

Instead of using <div>, try substituting it with a different HTML page

Seeking assistance on an HTML page project that involves jQuery, CSS, and HTML without server-side integration. Encountering an issue when attempting to replace a <div> with content from another HTML file saved on my computer. The main page code sni ...

Is there a way I can turn off the dragging functionality in my situation?

Is there a method to disable the dragging functionality within a draggable element? $('#dragitem').draggable({ scroll : false, drag: function(event, ui){ //check if condition is met if(†...

AngularJS asynchronous task

Currently, I am facing the challenge of running an asynchronous task to determine if the mobile GPS device is enabled and also to make a query to my web service. While I have methods in place to check the GPS and connections to my webservice, the issue l ...

Utilizing Jquery functions within the AngularJS framework

Utilizing Uikit along with its pagination feature, I am attempting to implement this function for changing the page: $('[data-uk-pagination]').on('uk-select-page', function(e, pageIndex){ console.log("page " + pageIndex); ...

Utilizing the JSON File in Your HTML Webpage: A Comprehensive Guide

I'm currently trying to integrate the following JSON file into my HTML page. <html> <head> <title> testing get</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> ...

JavaScript inquiry

How do you typically utilize JavaScript in your projects? I often use it for form validation, creating dropdown menus, and more. Do you have any unique ways of using JavaScript? Personally, I find jQuery to be a superior tool in certain situations... ...

Error with Cross-Origin Resource Sharing (CORS) on my website

During the development of a website, I disabled web security in order to bypass CORS using the command chrome.exe --disable-web-security --user-data-dir=/path/to/foo However, after successfully completing the website and uploading it to my domain, I enco ...

The 'Set-Cookie' response header failed to be recognized for a subsequent HTTP request

When a user successfully logs in, their information is stored in a cookie using the "Set-Cookie" response header. However, I am facing an issue where the cookie seems to get lost when making subsequent requests from the client. As a result, the server trea ...