1

I am calling a controller method Imperatively and in the response/Success, I am trying to update the @track property but its giving me an undefined error. Below is the code.

import { LightningElement, track } from 'lwc';
import findLocation from '@salesforce/apex/HomePageController.findLocation';

export default class HomePage extends LightningElement {
    /* eslint-disable no-console */
    @track locationName;
    @track showSpinner = false;


    handleInputField(event){
        if(event.target.name === 'location'){
            this.locationName = event.target.value;
        }
    }

    handleClick(event){
        if(event.target.name === 'search_location'){
            //alert('location clicked');
            this.showSpinner = true;
            this.getLocation(this.locationName);

        }else if(event.target.name === 'search_resturant'){
            console.log('search ResurantClicked');
            this.showSpinner = false;
        }
    }

    getLocation(location){
        findLocation({locationName: location}).then(function(result){
            console.log(result);
            this.locationName = result;
            this.showSpinner = false;
        }).catch(function(error){
            //this.showSpinner = false;
            console.log(error);
        });
    }

}

this.showSpinner = false and this.location = result; is giving me error "TypeError: Cannot set property 'locationName' of undefined".

What I am missing.

2 Answers 2

5

That is because of lexical scoping - this scope is undefined in unnamed function as callback.

You can use arrow function to correct it and scope of this will be class in it.

getLocation(location) {
    findLocation({ locationName: location })
        .then((result) => {
            console.log(result);
            this.locationName = result;
            this.showSpinner = false;
        })
        .catch((error) => {
            //this.showSpinner = false;
            console.log(error);
        });
}
0
findLocation({ locationName: location }).then(
    result => {  
        console.log(result);
        this.locationName = result;
        this.showSpinner = false;
    },  
    error => {  
      //this.showSpinner = false;
        console.log(error);
    }
);

Referral Link : https://salesforceblog.tumblr.com/tagged/lwc

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .