Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
Pulling information from OpenWeatherMap API when state (country) changes

Currently, I am only able to pull information when the name of the country is already loaded, I add the code, save it, then it's updated on localhost. But when I type in another country I get the error of Uncaught TypeError: Cannot read properties of undefined (reading 'temp'). For example, my code {weather.main.temp} works but only when the state = "france" is already set before.

My sub component:

const WeatherInfo = ({ country }) => {
    const [weather, setWeather] = useState({});
    useEffect(() => {
        axios
            .get(`https://api.openweathermap.org/data/2.5/weather?q=${country.capital}&appid=${api_key}&units=imperial`)
            .then(response => {
                console.log(response.data)
                setWeather(response.data)
            })
    }, [country])
    return (
        <div>
            <h3>Weather in {country.capital}</h3>
            <p><b>Temperature</b>{weather.main.temp}</p>
        </div>
    )
}

enter image description hereenter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

weather is initialized as an empty object when WeatherInfo is created. Therefore weather.main is undefined and you get the error when you try to get the attribute temp from undefined.

You can resolve this by having some conditional chaining or some ternary operators depending on what you want displayed when weather is an empty object.

return (
    <div>
        <h3>Weather in {country.capital}</h3>
        <p><b>Temperature</b>{weather.main?.temp}</p>
    </div>
)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!