Greetings to everyone,
I have really no experience in working with class components as I have been using the normal functional easy ones but recently started a project that requires the class component,
I have the following state variable -
this.state = {
current: "City X"
};
Now in the methods for this class, I have a function -
codeAddress(geocoder) {
var marker;
var data = this.state.data;
marker.addListener("click", () => {
// On click - The state value of 'current' should update to another value.
this.setState({current: 'City Y'});
setTimeout(() => {
var pointA = new google.maps.LatLng(54.976713, -1.60728);
var request = {
origin: pointA,
destination: location,
travelMode: 'DRIVING'
};
directionsService.route(request, function (result, status) {
if (status == 'OK') {
directionsRenderer.setDirections(result);
}
});
}, 2000)
});
}
However this code gives an error that TypeError: Cannot read properties of undefined (reading 'setState')
I have binded all the functions in the constructor and tried a bunch of different techniques of updating the state value but haven't been able to figure it out exactly just yet.
For what it looks like it seems like you have a problem with the scope of this,
Did you bind the codeAddress Function inside the constructor?
constructor( props ){
super( props );
this.codeAddress = this.codeAddress.bind(this);
}
So what is happening is that JavaScript is trying to access the this but inside a normal
Function (not an arrow function) and the this is just an object with no properties in your case.
With the bind Function we are binding the this we have in our class to that function so when you call this It will get you the this Of the class itself and will let you access all of it’s properties
Follow up on my previous answer One solution you can do is to add a binding function and call it inside the callback
const setCurrentOnMarkerClick = (function() {
this.setState({current: 'City Y'});
setTimeout(() => {
var pointA = new google.maps.LatLng(54.976713, -1.60728);
var request = {
origin: pointA,
destination: location,
travelMode: 'DRIVING'
};
directionsService.route(request, function (result, status) {
if (status == 'OK') {
directionsRenderer.setDirections(result);
}
});
}, 2000)
});
}).bind(this);
marker.addListener("click", setCurrentOnMarkerClick)