Geolocation in React

Hi everyone, I'm trying to get the user's location and then display some weather data but I'm running into some trouble along the way. Code:
const [location, setLocation] = useState("");
useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => {
setLocation(
"" + position.coords.latitude + "," + position.coords.longitude
);
axios.post("/api/hello", { location }).then((response) => console.log(response.data));
});
});
const [location, setLocation] = useState("");
useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => {
setLocation(
"" + position.coords.latitude + "," + position.coords.longitude
);
axios.post("/api/hello", { location }).then((response) => console.log(response.data));
});
});
The problem is the location is not being set in the early stage and is taking some time, leading to axios posting the data as
location: ''
location: ''
which ends up breaking the code. How do I do this properly?
2 Replies
Daryl
Daryl2y ago
GitHub
react-hook-geolocation/index.js at main · bence-toth/react-hook-geo...
A React hook to access data from the Geolocation API - react-hook-geolocation/index.js at main · bence-toth/react-hook-geolocation
Daryl
Daryl2y ago
I think the best is to get first the coordinates, and then do whatever you want.
Want results from more Discord servers?
Add your server