Search code examples
typescriptionic-frameworkionic3

How to fix cannot read property error in foreach loop


I have a foreach loop where i fetch data from firebase. i want to set a global variable to hold the "spotrating" (a property of each object). But when i call the global variable inside the forEach loop i get an error "cannot set property spotrating of undefined "

when i try to log the global variable in every other part of the code it works but when i do it in the forEach loop it doesnt work

spotrating: any;

Later in my code

temparr.forEach(function(firebaseSpot) {
        console.log(this.spotrating);
 });

I expect to get the value of the spotrating printed out to the console but i keep getting the error. "cannot read property spot rating of undefined"


Solution

  • The scope of this refers to your function because you did not use fat arrow notation. spotrating is not defined in your function. If you want this to refer to the outside function (the one calling it), use fat arrow notation as below. Scoping will bite you. I use fat arrow by default unless I want the scope of a callback or function to be that callback or function. Normally I don't.

    temparr.forEach(firebaseSpot => {
            console.log(this.spotrating);
     });
    

    Docs

    Edit: Using an arrow function is not actually changing the scope of the function as I used to think, my usage of the word scope above is not completely correct. An arrow function has its own scope.

    So while scope isn't changing, the value of this is changing. A normal function creates its own this while an arrow function does not as described here.

    In arrow functions, this retains the value of the enclosing lexical context's this. In global code, it will be set to the global object