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

221
Vistas
Uncaught TypeError: Cannot read properties of undefined (reading 'name') - ReactJS
import Info from "./components/Info";
import Search from "./components/Search";
import axios from "axios";
import { useEffect, useState } from "react";

const App = () => {

  const API_KEY = `<REDACTED>`
  const baseURL = `http://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=`

  const [weatherData, setWeatherData] = useState({})
  const [search, setSearch] = useState('London')
  const [error, setError] = useState('')

  useEffect(() => {
    axios.get(`${baseURL + search}`)
      .then(resp => {
        setWeatherData(resp.data)
      })
      .catch(error => setError(error.message))
  }, [search])

  console.log(weatherData.location.name);

  return (
    <div className="App">
      <h1 style={{ textAlign: 'center', marginBottom: '2rem' }}>{error}</h1>
      <Search setSearch={setSearch} />
      <div className="container">
        <Info weatherData={weatherData} />
      </div>
    </div>
  );
}

export default App;

I'm trying to create a weather app in react. I'm using the weather API that you can see in the code (maybe you should take a look at the API structure also). When I console log weatherData.location I get the normal weather data. But when I try weatherData.location.name I get the error that says: Uncaught TypeError: Cannot read properties of undefined (reading 'name'). I've started learning React two weeks ago so I'm still a beginner... Thank you.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This occurs when the API has not sent a response yet and weather data is still empty. I'd recommend adding a [loading,setLoading] state and setting that to true by default. Then set that to false in the .then(resp => function. Make an if statement to check if loading is false, and if so then print/render the contents of weatherData.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to add ternery operator in the console.log

like console.log(weatherData? location ? .name ) or You can try console.log(weatherData && weatherData.location && weatherDataname.location.name)

its happening becaus in initial state it cant read the value of name because probabaly its an empty string .

try this method .

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