Search code examples
javascriptreactjsfrontendfetch-apiopenweathermap

Why when i send a fecth requst to Open Weather API in React JS. React first return me undefined an after that data?


I watn to make Weather App. I just start study react. I do a fetch request to Open Weather API to get a weather data. When i consol.log(data) and update my page, React first return me undefined and after that data. I can't use data in other components because data is undefined.

App.jsx

function App() {
    const [weatherData, setWeatherData] = useState()
    useEffect(()=>{
        requestWeather('London')
    }, [])
    let requestWeather = async (city)=> {
        try {
            const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=4e4ff6f3165d9a027265ab73068e5a3a&mode=JSON`
            fetch(url)
            .then(data => data.json())
            .then(data => {
                setWeatherData(data)
            })
        } catch (error) {
            console.log(error);
        }
    }
    console.log(weatherData);
    return (
        <>
            <div className="wrapper">
                <Weather weather_data={weatherData}/>
            </div>
        </>
    )
}

Weather.jsx

export default function Weather({weather_data}){
    return(
        <div>{weather_data.name}</div>
        // There '.name' display name of city

    )
}

When i run that i got this errors ERRORS


Solution

  • No default value was specified for the state:

    const [weatherData, setWeatherData] = useState();
    

    So it defaults to undefined. You could add any default you like. For example, this would default to an empty object:

    const [weatherData, setWeatherData] = useState({});
    

    Or you could not render the Weather component if the value is "falsy":

    <div className="wrapper">
      { weatherData ? <Weather weather_data={weatherData}/> : null }
    </div>
    

    Or you could handle undefined within the Weather component itself:

    <div>{weather_data?.name}</div>
    

    Unrelated, but you'll also want to get in the habit of terminating statements with semi-colons. JavaScript is forgiving about omitting semi-colons, but programmers should not be. It's one of those things that will work just fine right up until the moment it doesn't.