Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda