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.

4

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);
        });
}
| improve this answer | |
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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.