Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get user location immediately page loads (React)

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>
    )
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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} />}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading