Search code examples
reactjsgoogle-mapssetstategoogle-places-autocomplete

Problem in setState in react component updating data received by google maps API


I am trying to setState of the address and coordinates as given by the "react-places-autocomplete". I have already stored those components by only issue is in updating it However, the changes are not updating and even though the program compiles as soon as I select a place it crashes. Especially for getLatLng there isn't enough documentation for me to understand if I have to access another component within that. How do I update the state of the address and coordinates via handleSelect?. Thanks!

import React, { Component }  from "react";
import PlacesAutocomplete, {
  geocodeByAddress,
  getLatLng
} from "react-places-autocomplete";

export default class Itinerary extends Component {
  constructor(props) {
    super(props);

    this.state = {
      address:"",
      coordinates:{lat: null,lng: null}
    };

  }

  Create2DArray(rows,columns) {
    var x = new Array(rows);
    for (var i = 0; i < rows; i++) {
        x[i] = new Array(columns);
    }
    return x;
 }

 handleChange = address => {
  this.setState({ address });
};


handleSelect = address => {
  const results = geocodeByAddress(address);
  const latLng = getLatLng(results[0]);

  this.setState({ coordinates: latLng });

};

  render() {

  return (
    <div className="container">
    <div className="row">
    <div className="col-md-6 mt-5 mx-auto">
      <PlacesAutocomplete
        value={this.state.address}
        onChange={this.handleChange}
        onSelect={this.handleSelect}
      >
        {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
          <div>
            <h1>Latitude: {this.state.coordinates.lat}</h1>
            <h1>Longitude: {this.state.coordinates.lng}</h1>

            <input size="50" height="40"{...getInputProps({ placeholder: "Type address" })} />

            <div>
              {loading ? <div>...loading</div> : null}

              {suggestions.map(suggestion => {
                const style = {
                  backgroundColor: suggestion.active ? "#41b6e6" : "#fff"
                };


                return (
                  <div {...getSuggestionItemProps(suggestion, { style })}>
                    {suggestion.description}
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </PlacesAutocomplete>
    </div>
    </div>
    </div>
  );
  }
}

Solution

  • geocodeByAddress and getLatLng are asynchronous functions so you have to wait these function until receiving data (read more about geocodeByAddress here). In handleSelect, results[0] is undefined when selecting, so that why your component is crashed. You should try this:

    export default class Itinerary extends Component {
      ...
      handleSelect = async address => {
        const results = await geocodeByAddress(address);
        const latLng = await getLatLng(results[0]);
    
        this.setState({ coordinates: latLng });
      };
      ...
    }