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:

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

Nested React Components in React Router Components

class AppRoutes extends Component { render () { return ( <Suspense fallback={<Spinner/>}> <Switch> <Route exact path="/" component={ HomePage } /> <Route exact path="/acti ...

Techniques for Grouping an Array of Objects by a Specific Value Key in Angular

I have the following array that needs to be grouped by section_name in HTML. Additionally, I need to first check if the length of the array values for section_name is greater than zero before displaying the results grouped by section_name. I hope my expl ...

Troubleshooting: Issue with Firebase callable function execution

In my index.js file, I have the following code snippet: const firebase = require("firebase"); const functions = require('firebase-functions'); // Firebase Setup const admin = require('firebase-admin'); const serviceAccount = require(&a ...

Error: Attempting to update the value of 'ordersToDisplay' before it has been initialized in a re-render of React. This results in an Uncaught ReferenceError

Trying to dynamically update the document title to include the order number by clicking a button to display different numbers of orders from an array on the screen. The process involves importing a JSON file, filtering it based on user input, calculating ...

The Protected Routes in React Router Dom persistently redirecting

I am currently implementing protected routes in my Redux and Pure React app using React Router Dom. The issue I am facing is that when I navigate to /profile/edit and then refresh the page, it automatically redirects me to /login and then to /profile. I ha ...

Typescript throws an error when attempting to return an array of strings or undefined from a function

I created a shallow differences function that compares two arrays of strings and returns either undefined (if the arrays are different lengths) or a string array containing matching characters at corresponding indexes. If the characters don't match, i ...

Having difficulty rendering JSON data on an HTML webpage

Currently, I am working on an API App that utilizes the Foursquare API. With the help of my getRequest function, I am able to obtain results in JSON format, which are then displayed in my console.log. However, the challenge lies in parsing the data from J ...

Having trouble setting up Amazon Cognito Auth JS with an Angular 4 application and a SAML identity provider

I've been working on integrating SAML Service provider with AWS Cognito pool. Despite going through numerous documents and attempting to implement it, I'm facing an issue where the redirection to the Microsoft login page is not happening when I c ...

Challenges encountered when setting a value to a custom directive via property binding

I'm working on a question.component.html template where I render different options for a specific question. The goal is to change the background color of an option to yellow if the user selects the correct answer, and to red if they choose incorrectly ...

Postgres Array intersection: finding elements common to two arrays

I'm currently developing a search function based on tags, within a table structure like this CREATE TABLE permission ( id serial primary key, tags varchar(255)[], ); After adding a row with the tags "artist" and "default," I aim ...

Steps to generate a fresh array from a given array of objects in JavaScript

Looking to transform an existing array into a new array of objects in Vue.js. Here's the initial array : import { ref } from 'vue'; const base_array = ref([ {id: 1, name: Pill, timing: [morning, noon, evening, night]}, {id: 2, name: Ta ...

Conceal the React button once it has been pressed

In my checklist of questions, I have set up a system where the first button is shown if any checkboxes are selected. If no checkbox is selected, then the second "Submit" button is displayed. Upon clicking submit, a message appears inside. Additionally, for ...

Angular 7 router navigate encountering a matching issue

I created a router module with the following configuration: RouterModule.forRoot([ {path: 'general', component: MapComponent}, {path: 'general/:id', component: MapComponent}, {path: '', component: LoginComponent} ]) Sub ...

Error encountered in amCharts Serial Chart when data parsing is enabled with the setting "parseDates": true which resulted in the failure to display data

Using Spring as a webservice, I received a JSON response with stock data: [ { "date": "2016-04-17", "open": 1085.0, "high": 1092.2, "low": 1072.0, "close": 1088.3, "volume": 54100, "value": 1088.3 }, { "date": "2016-04-14", "open": 1081. ...

Typescript: Securing Data with the Crypto Module

I am currently working on encrypting a password using the built-in crypto module. Previously, I used createCipher which is now deprecated. I am wondering if there is still an effective way to achieve this. Here is the old code snippet: hashPassword(pass: ...

Tips on displaying tooltips on multiple graphs in Highcharts using Vue 3

I am currently utilizing vue3-highcharts in conjunction with Highcharts. My goal is to replicate a similar functionality as shown in this example: https://codepen.io/lzl124631x/pen/KLEdby?editors=1010. However, I am unsure about the correct syntax for impl ...

Internet Explorer is throwing unexpected routing errors in Angular 2

I have a spring-boot/angular 2 application that is working perfectly fine on Chrome, Safari, Opera, and Edge. However, when accessed through Internet Explorer, the app directly routes to the PageNotFound component. I have tried adding shims for IE in the i ...

Issue with exclude not functioning in tsconfig.json for Angular Typescript deployment

I am encountering an issue with a module within the node_modules directory while compiling my Angular 4 project. The error messages I'm receiving are as follows, even after attempting to exclude the problematic module in the tsconfig.json file. Can an ...

A Comprehensive Guide to Handling Errors in Angular 4: Passing the err Object from Service to Component

Currently, I am in the process of developing a login page using Angular for the front-end and Spring Security for the back-end. Everything appears to be functioning correctly, except for handling exceptions when attempting to catch errors from the service ...

Animating the Click Event to Change Grid Layout in React

Can a grid layout change be animated on click in React? For instance, consider the following component: import { Box, Button, styled, useMediaQuery } from "@mui/material"; import Row1 from "./Row1"; import React from "react"; ...