Search code examples
reactjslistenerbindtypeerrorsetstate

React: How to use setState in AddListener()?


I have a method that calls an addListener to data that does not exist yet until you've clicked on a button. However, as I try to set that data inside a state, I get the following error:

TypeError: this.setState is not a function

I've tried binding my dataHandler like this:

this.dataHandler = this.dataHandler.bind(this)

yet it still returns this error. What am I forgetting here?

constructor(props){
    super(props)
    this.state = {
        selActive: 4,
        loaded: false,
        mapInfo: ''
    }
    this.onScriptLoad = this.onScriptLoad.bind(this)
    this.dataHandler = this.dataHandler.bind(this)
}

dataHandler = (getJson) => {
    fetch(getJson)
        .then(response => response.json())
        .then(featureCollection => 
            dataLayer = map.data.addGeoJson(featureCollection)
        );
    map.data.addListener('mouseover', function(event) {
        map.data.revertStyle();
        map.data.overrideStyle(event.feature, {fillColor: 'blue'});
        // THIS IS WHERE I ADD MY SETSTATE. 
        // HOWEVER, THIS RETURNS AN ERROR ON HOVER
        this.setState({mapInfo: event.feature.countryNL})
    });
}

Solution

  • In JavaScript this always refers to the "owner" of the function we're executing, or rather, to the object that a function is a method of. Use arrow function instead. An arrow functions doesn't have its own this/super/arguments binding. It inherits them from its parent lexical scope.

    map.data.addListener('mouseover', (event) => {
        map.data.revertStyle();
        map.data.overrideStyle(event.feature, {fillColor: 'blue'});
        // THIS IS WHERE I ADD MY SETSTATE. 
        // HOWEVER, THIS RETURNS AN ERROR ON HOVER
        this.setState({mapInfo: event.feature.countryNL})
    });
    

    Reference: