'navigator.getCurrentPosition won't save the values in state variables

I have some issues with getting the current position I've made a function which will save the latitude and longitude in lat/lng variables but i need to push the button 2 times in order to get the values. First time that I'm pushing the button give me the initial value: null, second time it will succesfully upgrade my state variables

Can Someone explain me why do I need to press it two times?

    const [lat, setLat] = useState(null);
    const [lng, setLng] = useState(null);
    
    const getLocation = () => {
        navigator.geolocation.getCurrentPosition((position) => {
            setLat(position.coords.latitude);
            setLng(position.coords.longitude);
    })

    console.log('lng: ' + lng + ' and lat: ' + lat);

    if (lat !== null && lng !== null)
    { 
        getData()//here i am calling an API
    }
        
      // make sure to catch any error
    //  .catch(console.error);
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source