I'm using custom hook useGeolocation() to get the user location using navigator.geolocation api. I'm trying to set the latitude and logitude obtained by this hook to set coordinates using useState , which is not working. I can console log the coordinates returned , but unable to assign it using useState hook.
useGeolocation() hook :
import React , {useEffect , useState}from 'react';
export default function useGeolocation() {
const [location , setlocation] = useState({
loaded:false,
errror:false,
coordinates:{lat:"",lng:""},
});
const onSuccess = (locn) => {
setlocation({
loaded:true,
errror:false,
coordinates :{
lat : locn.coords.latitude,
lng :locn.coords.longitude
}
})
}
const onError = (error) => {
setlocation({
loaded:true,
errror:true,
error,
})
}
useEffect(() => {
if(!("geolocation" in navigator)){
onError({
code :0,
message :"Geolacation not supported"
});
}
navigator.geolocation.getCurrentPosition(onSuccess ,
onError);
}, []);
return location;}
Form.jsx
import React, { useState } from "react";
import useGeolocation from "../hooks/useGeolocation";
function Form() {
const [formData, setFormData] = useState({
firstName: "",
email: "",
lat:"",
lng:"",
pickupAddress : "",
});
//useGeolocation hook
const location = useGeolocation();
return (
<form className="form">
<div className="form-container">
<input
type="text"
placeholder="First Name..."
value={formData.firstName}
onChange={(e) => {
setFormData({ ...formData, firstName: e.target.value });
}}
required
/>
<input
type="text"
placeholder="Donor Email .."
value={formData.email}
onChange={(event) =>
setFormData({ ...formData, email: event.target.value })
}
required
/>
{/* here I'm trying to setFormData for latitude ,
which is not working */}
<textarea
placeholder="Pickup Address .."
value={formData.pickupAddress}
onChange={(e) => {
if(location.errror){
alert("location access denied ..kidly allow location access");
return;
}
console.log(location);
console.log(JSON.parse(location?.coordinates.lat))
setFormData(
{ ...formData,
lati : JSON.parse(location?.coordinates.lat) })
setFormData({ ...formData,
pickupAddress: e.target.value });
console.log(formData);
}}
required
/>
<button type ="submit">
Submit
</button>
</div>
</form>
);
}
export default Form;