skip to Main Content

I have a problem with my weatherApp, the first API is working and I’m getting all of the data, but I also want to include air pollution but this isn’t working, I have the coordinates its asking for but the response I get is nothing to geocode. Anyone knows what I’m doing wrong?

console.log

function Forecasts() {
    const [data, setData] = useState({});
    const [city, setCity] = useState("");
    const [lat, setLat] = useState("");
    const [lon, setLon] = useState("");
    const [pollution, setPollution] = useState({});
    const apiKey = import.meta.env.VITE_API_KEY;

    const searchLocation = () => {
        // Fetch weather data
        const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
        axios.get(weatherUrl)
            .then((response) => {
                setData(response.data);
                setLat(response.data.coord.lat);
                setLon(response.data.coord.lon);
                console.log(response.data);
                console.log(response.data.coord.lat);
                console.log(response.data.coord.lon);

                // Fetch pollution data using coordinates
                const pollutionUrl = `https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${apiKey}`;
                axios.get(pollutionUrl)
                    .then((pollutionResponse) => {
                        setPollution(pollutionResponse.data);
                        console.log(pollutionResponse.data);
                    })
                    .catch((pollutionError) => {
                        console.error("Error fetching pollution data:", pollutionError);
                    });
            })
            .catch((error) => {
                console.error("Error fetching weather data:", error);
            });

        setCity("");
    }

I’m clueless at this point.

2

Answers


  1. Thе issuе you arе facing is rеlatеd to thе timing of thе lat and lon variablеs you arе trying to usе thе lat and lon valuеs to construct thе URL for fеtching air pollution data immеdiatеly aftеr calling sеtLat and sеtLon thе statе updatеs arе asynchronous so thе valuеs of lat and lon may not havе bееn updatеd yеt whеn you usе thеm to construct thе pollutionUrl this is why you arе gеtting thе "nothing to gеocodе" еrror

    Login or Signup to reply.
  2. Setting state in react js is asynchronous. You are using setLat() and setLon(), which are asynchronous here. At the time of second api call both the states are empty. Instead try below:

    function Forecasts() {
        const [data, setData] = useState({});
        const [city, setCity] = useState("");
        const [lat, setLat] = useState("");
        const [lon, setLon] = useState("");
        const [pollution, setPollution] = useState({});
        const apiKey = import.meta.env.VITE_API_KEY;
    
        const searchLocation = () => {
            // Fetch weather data
            const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
            axios.get(weatherUrl)
                .then((response) => {
                    setData(response.data);
            const latitude =response.data.coord.lat;
    
            const longitude =response.data.coord.lon;     
      
            setLat(latitude);
                        
            setLon(longitude );
                        console.log(response.data);
                        console.log(response.data.coord.lat);
                        console.log(response.data.coord.lon);
        
                        // Fetch pollution data using coordinates
                        const pollutionUrl = `https://api.openweathermap.org/data/2.5/air_pollution?lat=${latitude}&lon=${longitude}&appid=${apiKey}`;
                        axios.get(pollutionUrl)
                            .then((pollutionResponse) => {
                                setPollution(pollutionResponse.data);
                                console.log(pollutionResponse.data);
                            })
                            .catch((pollutionError) => {
                                console.error("Error fetching pollution data:", pollutionError);
                            });
                    })
                    .catch((error) => {
                        console.error("Error fetching weather data:", error);
                    });
        
                setCity("");
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search