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

220
Views
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 answers
Answer question

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 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!