0

I am using a class component. When I run this script, it plots the graphic, but in the next line when it calls the function computePM_from_ClickedPoint, I get the error below. The error refers to "this", but without it, I cannot call the function. Suggestions?

Error: Cannot read properties of undefined (reading 'computePM_from_ClickedPoint')

 
interface IProps {
  mapView: __esri.MapView | __esri.SceneView;
}
 
constructor(props) {
  super(props);
  this.enableMapClick = this.enableMapClick.bind(this);
}
 
enableMapClick = () => {
  var view = this.props.mapView;
    
  view.on("click", function (evt) {
    var point = new Point({
      longitude: evt.mapPoint.longitude,
      latitude: evt.mapPoint.latitude,
      spatialReference: view.spatialReference,
    });

    var pointMarker = new PictureMarkerSymbol({
      url: "https://static.arcgis.com/images/Symbols/Animated/EnlargeRotatingRedMarkerSymbol.png",
      height: "20px",
      width: "20px",
    });

    var graphic = new Graphic({
      geometry: point,
      symbol: pointMarker,
    });
    
    console.log(graphic)
    
    view.graphics.add(graphic);
    this.computePM_from_ClickedPoint(graphic.geometry);
  });
    
 computePM_from_ClickedPoint(screenPoint) {
    var mp = webMercatorUtils.webMercatorToGeographic(screenPoint, false);
    ----
    -----
    }
 
 render() {
    return (
      <div>
      <Button onClick={this.enableMapClick}>
         Click the Map
      </Button>
      </div>
      )}

tried unsuccessfully changing the call to:

this.computePM_from_ClickedPoint(graphic.geometry).bind(this);
  • try `onClick={() => this.enableMapClick()}`. This is a common issue with class-based components. If you use `this`, they need to be invoked as methods `this.something()`. Passing them as functions (`onClick={this.something}`) causes the `this` context to be lost. – CollinD Dec 29 '22 at 22:50
  • Thanks @CollinD. It didn't work. – Lefteris Koumis Dec 29 '22 at 23:07
  • Change your event handler to an arrow function. It's exactly the same issue. You're passing a `function` to `view.on` and expecting it to be invoked like a `method`. – CollinD Dec 29 '22 at 23:34
  • @CollinD I am not experienced in react. It seems that view.on seems to be working since the graphic is plotted on the map. Can you be more specific of what should change? – Lefteris Koumis Dec 30 '22 at 00:30
  • try ``` – NirG Dec 30 '22 at 01:04
  • @NirG. Post your response as an answer so I can accept it. – Lefteris Koumis Dec 30 '22 at 02:17

1 Answers1

0

Instead of bindingthis.computePM_from_ClickedPoint(graphic.geometry).bind(this) try to bind to this.enableMapClick on onClick event (this way you can call it with this/Class same specific object), something like.

render() { return (
<div>
  <button onClick="{this.enableMapClick.bind(this)}">Click the Map</button>
</div>
)}

For more details:- javascript-bind-method

DSDmark
  • 1,045
  • 5
  • 11
  • 25
Samil Abud
  • 31
  • 2