I'm encountering an issue when trying to access nested data from an object that I'm receiving from an API using the useContext hook in a React application. The error message I'm getting is: "Uncaught TypeError: Cannot read properties of undefined (reading 'forecastday')". Strangely, when I tried to access the same data using vanilla JavaScript, it worked without errors.
I suspect there might be something wrong with my Context.jsx file, but I can't pinpoint the exact issue.
OBJECT DATA
weatherReport = {
"location": {object Data},
"current": {object Data},
"forecast": {
"forecastday": [
{
"date": "2023-03-07",
"date_epoch": 1678147200,
"day": {
"maxtemp_c": 36.1,
"maxtemp_f": 97.0,
"mintemp_c": 17.4,
"mintemp_f": 63.3,
"avgtemp_c": 25.6,
"avgtemp_f": 78.1,
"maxwind_mph": 9.6,
"maxwind_kph": 15.5,
"totalprecip_mm": 0.0,
"totalprecip_in": 0.0,
"totalsnow_cm": 0.0,
"avgvis_km": 10.0,
"avgvis_miles": 6.0,
"avghumidity": 22.0,
"daily_will_it_rain": 0,
"daily_chance_of_rain": 0,
"daily_will_it_snow": 0,
"daily_chance_of_snow": 0,
"condition": {
"text": "Sunny",
"icon": "//cdn.weatherapi.com/weather/64x64/day/113.png",
"code": 1000
},
"UV": 7.0
},
},
}
React component code
import { useGlobalContext } from "../context"
const ForecastReport = () => {
const { forecast: { forecastday: [...forecastday] } } = useGlobalContext()
console.log(forecastday)
return <div className="forecast-box">
Forecast Report
</div>
}
export default ForecastReport
error on console
"Uncaught TypeError: Cannot read properties of undefined (reading 'forecastday')
vanilla js
const {forecast:{forecastday:[...forecastday]}} = weatherReport
console.log(forecastday);
console for vanilla js
(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
[https://replit.com/@djbravo12/WeatherApplicationOpenWeatherorg#src/context.jsx](my repl link)