I would be glad to have some help from you: I added 'react-places-autocomplete' to my app and i'm having an issue with getting some data.
I have a form with several inputs where we can search for a city.
On the first input, i'm looking for a city called "toulouse", and i click on the suggestion: it displays the right data on top of the search bar, but on the console, the name is ok but coordinates are null.
Still on first input, i'm now looking for a city called "bordeaux", and i click on the suggestion: it still displays the right data on top of the search bar, but on the console, it displays the name 'bordeaux', but the PREVIOUS coordinates from 'Toulouse'!
Do you have an idea why? Thank you very much for your help!
Here is the Search Component
import React, { useState, useContext } from 'react';
import PlacesAutocomplete, {
geocodeByAddress,
getLatLng,
} from 'react-places-autocomplete';
import CitiesContext from './CitiesContext';
export default function Search(props) {
const { cities, updateCities } = useContext(CitiesContext);
const [address, setAddress] = useState('');
const [coordinates, setCoordinates] = useState({
lat: null,
lng: null,
});
const handleSelect = async value => {
const results = await geocodeByAddress(value);
// we save the lat and long from the 1st result/ selected one
const latLng = await getLatLng(results[0]);
// Updating coordinates
setCoordinates(latLng);
// Updating address
setAddress(value);
const city = {
name: value,
coordinates,
};
updateCities(city);
console.log('Here is the city: ', city); // Name is OK, but coordinates are the previous ones !
};
return (
<div>
<PlacesAutocomplete
value={address}
onChange={setAddress}
onSelect={handleSelect}
>
{({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
<div>
<p>
latitude: {coordinates.lat} - longitude: {coordinates.lng}
</p>
<p>address: {address}</p>
<input {...getInputProps({ placeholder: props.placeholder })} />
<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>
);
}
```