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

229
Vistas
Cannot Read properties of undefined React. Log only works on object

I'm currently trying to create a weather website using weatherapi, but I'm running into a problem. If I log the object of location there's no error, but if I try to log anything deeper than that object, like the name of the city it cannot read properties of undefined. If I comment out the log when it's using the name of the city, then uncomment it again and don't reload the page, then it will log the name of the city without error.

import React from 'react';
import './index.css';
import Navbar from "./components/Navbar"
import {useState} from "react"
import Weather from './components/Weather';


function App() {
  const [inputData, setInputData] = useState({})
  const [currentWeather, setCurrentWeather] = useState([])
  const [loc, setLoc] = useState({loc:"Arlington"})
  let apiKey = "xxxxxxxx"
  // console.log("Location: "+ loc.loc)

  React.useEffect(() =>{///Finds weather data of certain location
    console.log(loc.loc)
    fetch(`https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${loc.loc}&aqi=no`)
    .then(res => {
      if(res.ok){
        return res.json()
      }
    })

    .then(data => {
      if(data !=null){//Only change currentWeather when there is data for it
        setCurrentWeather(data)
      }else{
        alert(`${loc.loc} was not found`)
      }
    })
  }, [loc])

  React.useEffect(() =>{///Finds locations with search bar
    fetch(`https://api.weatherapi.com/v1/search.json?key=${apiKey}&q=${loc.loc}&aqi=no`)
    .then(res => res.json())
    .then(data => {
      if(data.loc == null){
      }else{
        setLoc(data)
      }
    })
  }, [])

  
  //console.log(currentWeather.location.name)
  

  return (
    <div className="App">
      <Navbar inputData={inputData} setLoc={setLoc} setInputData={setInputData}/>
      <Weather currentWeather={currentWeather}/>
    </div>
  );
}

export default App;


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

0

A few issues I see:

  1. You are initializing currentWeather to an array, but it should probably be either undefined or an object ({}) based on your use of it. To fix this, use one of these:
const [currentWeather, setCurrentWeather] = useState()
// or
const [currentWeather, setCurrentWeather] = useState({})
  1. You are trying to access currentWeather.location.name before you have updated currentWeather to have those properties. That's why you're getting that error.

The best solution for this is to use optional chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

So try this:

console.log(currentWeather?.location?.name)
  1. Your console.log is just in the body of the function component, meaning it will only be called once (with the initial value), I think. To fix this, and log every time the value of currentWeather changes, you can do this instead:
React.useEffect(() => { console.log(currentWeather?.location?.name) }, [currentWeather])
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