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

260
Views
TypeError: Cannot read properties of undefined (reading 'country')

I'm trying to fetch data from an API and use that data in my app. But the problem is that when I try to get a certain object or data from the JSON I've just got from the API, I get a TypeError: Cannot read property 'country' of undefined. The property DOES exist. By the way, I'm using React.js. I really appreciate your help & guidance. Here is the code:

App.js

{typeof weather != 'undefined' ? (
  <div>
    <div className="location-box">
      <div className="location">
        
        {weather.name},{weather.sys.country} 
      </div>
      <div className="date"> {dateBuilder(new Date())} </div>
    </div>

    <div className="weather-box">
      <div className="weather-temperature">15*C</div>
      <div className="weather">Sunny </div>
    </div>
  </div>
) : ("NULL")}

Api from where we are going to fetched the data.

function App() {
  const [query, setQuery] = useState("");
  const [weather, setWeather] = useState({});

  const Search = (evt) => {
    if (evt.key === "Entre") {
      debugger;
      fetch(`${api.base}weather?q=${query}&units=metric&APPID${api.key}`)
        .then((res) => res.json())

        .then((result) => {
          setWeather(result);
          setQuery("");
          console.log(result);
        });
    }
  };
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you are certain that the property does exist, then it must be the initial render. You initialise the useStaet with {} but guard against undefined. So change useState({}) to useState().

const [weather, setWeather] = useState();

You can also add a null check when you read country.

{weather.name}, {weather.sys?.country}
about 4 years ago · Juan Pablo Isaza Report

0

The problem is because of your weather check: typeof weather != 'undefined' while your init value of weather is {}. In order to solve the problem don't set init value for weather. like this:

const [weather, setWeather] = useState();

So, in the first render weather value will be undefined and in the next render it contains your api response.

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!