I'm trying to use a geocode locator which returns longitude and latitude from a city name. This is supposed to be set as a state and used to display the city on a map. I can manage to fetch the results just fine, however, when I try to set the state, the state is null.
This is the code for the map component:
import React, { useState, useEffect } from "react";
import MapGL, { GeolocateControl } from "react-map-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import { OpenStreetMapProvider } from "leaflet-geosearch";
const Map = (props) => {
const [long, setLong] = useState(null);
const [lat, setLat] = useState(null);
useEffect(() => {
getCoords();
}, []);
const TOKEN =
"xxx.xxx.xxxx-xxxxx";
const [viewport, setViewPort] = useState({
width: "20%",
height: 400,
latitude: 6.122498,
longitude: 80.112597,
zoom: 12,
});
const _onViewportChange = (viewport) =>
setViewPort({ ...viewport, transitionDuration: 3000 });
const getCoords = async () => {
// setup
const provider = new OpenStreetMapProvider();
// search
const results = await provider.search({ query: props.currentCity });
console.log(results[0].x)
console.log(results[0].y)
setLong({ long: results[0].x });
setLat({ lat: results[0].y });
console.log(long);
console.log(lat)
};
return (
<div style={{ margin: "0 auto" }}>
<MapGL
{...viewport}
mapboxApiAccessToken={TOKEN}
mapStyle="mapbox://styles/mapbox/dark-v8"
onViewportChange={_onViewportChange}
></MapGL>
</div>
);
};
export default Map;
I've preset some values as latitude and longitude and rely on the console. logs, so the app doesn't break.
console.log(results[0].x)
console.log(results[0].y)
setLong({ long: results[0].x });
setLat({ lat: results[0].y });
console.log(long);
console.log(lat)
The first two logs prints the location just great. The last two, prints the initial state of the state, which is: null.
The city name comes from the props, which comes from a different component and it does work as it should.
<Map currentCity={currentCity}/>
I'm pretty sure it's something stupid but I cannot for my life figure out what. The map is a mapbox, I'm using OpenStreetMapProvider from leaflet.
I've tried different providers but to no success. I'm pretty sure that I'm doing something wrong in my async call. I think that the state sets before the call is finished. I've tried using promises but nothing changes.
Thanks.