Search code examples
javascriptreactjsreact-map-gl

Loop through state and create multiple components


I'm trying to display location coordinates (of vehicles) on a map with data that I'm fetching every 3 seconds. Every time I fetch the data (array of objects with attribute "Longitude" and "Latitude"), the state will update and I want to update the "markers" on a map to reflect the vehicles' latest positions.

I know I'm fetching the data but the markers are not showing up. Is there something wrong with the way I loop?

class Mapbox extends Component {
  constructor(props){
    super(props)
    this.state = {
      active_vehicles: {},
    };
  }

  componentDidMount() {
    this.interval = setInterval(() => this.fetchData(), 3000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }


  fetchData = async () => {
    let url = `${request_url}`
    const response = await fetch(url, {
      method: "GET",
      headers: {
        "Accept": "application/json",
      }
    });
    const body = await response.json()
    this.setState({ active_vehicles: body })
  }

  createMarkers = () => {
    let markers = []

    if(this.state.active_vehicles){
      for (let i = 0; i < this.state.active_vehicles.length; i++) {
        markers.push(
        <Marker latitude={this.state.active_vehicles[i]["Latitude"]} longitude={this.state.active_vehicles[i]["Longitude"]}>
          <div>x</div>
        </Marker>
        )
      }
      return markers
    }
  }

  render() {
    return (
      <ReactMapGL
        // mapbox API access token
        mapboxApiAccessToken={MAPBOX_TOKEN}
        mapStyle="mapbox://styles/mapbox/dark-v9"
        {...this.state.viewport}
        onViewportChange={(viewport) => this.setState({viewport})}>

        <div>
          {this.createMarkers()}
        </div>

      </ReactMapGL>
    );
  }
}

Solution

    1. Correct this.active_vehicles to this.state.active_vehicles (OP has corrected after I posted my comment)
    2. Add key attribute to the Marker component inside the for loop: <Maker key={i} ...