I am trying to get user location immediately page loads so i can pass it as a prop to the timeline function. But I am having problems with it. The timeline latitude and longitude props on the timeline are null. How do i fix this please. only dirty tricks that have caused the page to load really slowly have worked so far. I am sure there is a better way. Please help!
function Home(){
const [latitude, setLatitude] = useState(null);
const [longitude, setLongitude] = useState(null)
useEffect(() => {
getCoords()
}, [])
const getCoords = async () => {
const pos = await new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
setLatitude(pos.coords.latitude)
setLongitude(pos.coords.setLongitude)
};
return(
<div>
<NavBar></NavBar>
<Timeline latitude={latitude} longitude={longitude}></Timeline>
</div>
)
}
CodePudding user response:
It will try to fetch the location when that component mounts, but it will have another render cycle before those are applied to state. A common pattern is to only render the component dependent on those props when they're available
{latitude && longitude && <Timeline latitude={latitude} longtide={longitude} />}