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

261
Views
TypeError: no se pueden leer las propiedades de undefined (leyendo 'país')

Estoy tratando de obtener datos de una API y usar esos datos en mi aplicación. Pero el problema es que cuando trato de obtener un determinado objeto o datos del JSON que acabo de obtener de la API, obtengo un error de tipo: no se puede leer la propiedad 'país' de undefined. La propiedad SÍ existe. Por cierto, estoy usando React.js. Realmente aprecio su ayuda y orientación. Aquí está el código:

Aplicación.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 desde donde vamos a buscar los datos.

 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

Si está seguro de que la propiedad existe, entonces debe ser el renderizado inicial. Inicializas useStaet con {} pero te proteges contra undefined . Así que cambia useState({}) a useState() .

 const [weather, setWeather] = useState();

También puede agregar un cheque nulo cuando lea country .

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

0

El problema se debe a su verificación del clima: typeof weather != 'undefined' mientras que su valor inicial de tiempo es {} . Para resolver el problema, no establezca el valor inicial para el clima. como esto:

 const [weather, setWeather] = useState();

Entonces, en el primer renderizado, el valor del clima no estará undefined y en el siguiente renderizado contiene su respuesta API.

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!