Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda