javascriptreactjsstatejsxpageload

The information is not displayed after the first load of the page, only after rerendering the second time. Why?


The information from openweathermap API is not displayed after the first load of the page, only after rerendering the second time. I can't understand why.

const [latitude, setLatitude] = useState('')
const [longitude, setLongitude] = useState('')

const [data, setData] = useState({})
const [location, setLocation] = useState('')

const metric_units = 'metric'
const API_KEY = '5bb165082febcb3965e5bded762c5711'
const API_URL = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&q=${location}&appid=${API_KEY}&units=${metric_units}`

// Gets users location from API by latitude and longitude
useEffect(() => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      setLatitude(position.coords.latitude)
      setLongitude(position.coords.longitude)

      axios.get(API_URL).then((response) => {
        setData(response.data)
        setMyLocation(response.data.name)
        setLocation(myLocation)
      })
    })
 } else {
    alert("Geolocation is not supported by this browser.")
  }
}, []);

Solution

  • I'm not sure but in my perspective you would change your code like the below

    useEffect(() => {
    navigator.geolocation &&
      navigator.geolocation.getCurrentPosition((position) => {
        setApiUrl(
          `https://api.openweathermap.org/data/2.5/weather?lat=${position.coords.latitude}&lon=${position.coords.longitude}&q=${location}&appid=${API_KEY}&units=${metric_units}`
        );});}, []);
    

    Now the first render set Lat & Long and now another useEffect fetch data like the blow

     useEffect(() => {
    axios.get(apiUrl).then((response) => {
      setData(response.data);
      setMyLocation(response.data.name);
      setLocation(myLocation);
    });}, [apiUrl]);
    

    Becuase the first useEffect will work at the first render and create your apiUrl and followed by setting a new apiUrl the second useEffect would be render again to fecth data. Please let me know if you try it.