Jerlam
Jerlam

Reputation: 1101

How to handle props and states to avoid infinite loops?

I have a component which gets props from his parents, I am checking if this.props.addMarker is true in componentDidUpdate(), if true it triggers a function in which there is a setState.

You can imagine what's next: the setState triggers the componentDidUpdate() function, which checks if this.props.addMarker is true...and so on...

What should I do to avoid this type of issue?

Here is my code:

componentDidUpdate() {  
    if(this.props.addMarker) {
      const place = this.props.coordinatesToCenter;
      const coord = place.coordinates;

      this.addMarkerProcess(place.place_name, place.place_type, coord.lon, coord.lat);
    }
}

addMarkerProcess(name, maki, xCoordinate, yCoordinate) {
    const data = {
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: [xCoordinate, yCoordinate]
      },
      properties: {
        // place:
        // login:
        lat: yCoordinate,
        lon: xCoordinate,
        color: "#00FFFF"
      }
    };

    if(this.state.clickIsEmpty) {
      data.properties.place = this.state.userNewPlaceInput;
      data.properties.login = this.state.userNewTypeInput;
    } else {
      data.properties.place = name;
      data.properties.login = maki;
    }

    const prevGeoJson = _.cloneDeep(this.state.geoJson);
    console.log("prevGeojson1", prevGeoJson)
    // map only rerenders geoJSONLayer if geoJSONLayer.data is a new instance:
    const geoJson = Object.assign({}, this.state.geoJson);
    geoJson.features.push(data);

    this.setState(prevState => ({
      prevGeoJson: prevGeoJson,
      geoJson: geoJson,
      currentMarker: data
    }));

    let canvas = document.querySelector('.mapboxgl-canvas');
    if(canvas.classList.contains("cursor-pointer")) {
      canvas.classList.remove("cursor-pointer");
    }
  }

Upvotes: 0

Views: 391

Answers (1)

Dupocas
Dupocas

Reputation: 21347

componentDidUpdate() is invoked immediately after an update, so if you call setState() without being wrapped in a condition, you will inevitably cause the infinite loop to occur. You could call setState() based on a comparison between new and previous props.

componentDidUpdate(prevProps) {
    if(this.props.data !== prevProps.data) 
        this.fetchNewData(this.props.data);
}

Upvotes: 2

Related Questions