Pushing to @track array variable says cannot read property push of undefined

This may be a super simple solution, I had this below code copied from another location from the same project, which works really well. Brought it in to another section, changed the variable names, for some reason it doesn't work. I get the error "Cannot read property 'push' of undefined". Also the console.log below get the correct length.

@track cities = []; markerClick(e) { let province = ''; getCitiesByProvince({ province: province, }).then(result => { console.log(result.length) for (let i = 0; i < result>


function run when clicked on a map marker.

export default class MduPenetration extends LightningElement { @track provinces = []; @track cities = []; @wire(onLoadProvinces) provStats({ data }) { if (data) { for (let i = 0; i < data xss=removed> { const el = this.template.querySelector(".map-root"); let mymap = L.map(el).setView([54.139503, -96.653471], 5); L.tileLayer('https://api.mapbox.com/styles/v1/sumchans', { tileSize: 512, zoomOffset: -1 }).addTo(mymap); let bcPopup = L.circle([this.provinces[0].latitude, this.provinces[0].longitude], { id: 'BC', color: 'white', fillColor: '#38c', fillOpacity: 0.5, radius: (this.provinces[0].penetration) * 2500 }).addTo(mymap).on('click', this.markerClick); }); } markerClick(e) { getCitiesByProvince({ province: 'BC' }).then(result => { if (result) { // console.log(this.cities); This says undefined for (let i = 0; i < result>

 What is reason of getting typeerror: cannot read property 'push' of undefined?

Answered by Lucas Jackson

Since it's a callback function, the scope of "this" is changing to the Leaflet library (or possibly a marker class, etc). If you want to maintain the scope of the component, you should use bind to keep the correct scope:

}).addTo(mymap).on('click', this.markerClick.bind(this));

This will make sure you're in the component's scope, and not in the marker's scope.



Your Answer

Interviews

Parent Categories