skip to Main Content

I’m trying to access the data from a nested array which is stored in the data of the object. this data I’m getting from API through "useContext" hook in react. when refreshing the after writing code for accessing the data it is giving me the error "Uncaught TypeError: Cannot read properties of undefined (reading ‘forecastday’)" but when tried to access it in vanilla js it showed on my console. Now don’t know what is really going on in my code. But what I feel here is I guess something is wrong in my Context.jsx page.

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)

3

Answers


  1. it’s getting the error because when your page will refresh or render that time context data will be not set in the context state so. it’s getting "Uncaught TypeError: Cannot read properties of undefined"

    You need to write the condition when the context state value is stored then you will access it.

    Login or Signup to reply.
  2. forecast probably isn’t available yet and so you’re getting undefined issues.

    Try updating in a useEffect hook after confirming that forecast is defined.

    You could do something like:

    import { useState, useEffect } from "react";
    import { useGlobalContext } from "../context";
    
    const ForecastReport = () => {
      const { forecast } = useGlobalContext();
      const [forecastDay, setForecastDay] = useState(null);
    
      useEffect(() => {
        if (forecast) {
          setForecastDay(forecast.forecastday);
        }
      }, [forecast]);
    
      return (
        <div className="forecast-box">
          Forecast Report
        </div>
      );
    };
    

    You could then do whatever you like with forecastDay once it’s value has changed from null.

    Login or Signup to reply.
  3. I am sure, this issue occurs because of your context.
    So it will be much more clear when you share your context code.

    By the way, I have tested this on my side. But works all fine.

    Here is my code (App and Data Component).

    // import context
    import { DataContextProvider, useData } from "./contexts/DataContext";
    
    const Data = () => {
      const {
        people: {
          users: [...usersInfo],
        },
      } = useData();
      console.log(usersInfo);
      return <div>hello Data</div>;
    };
    
    const App = () => {
      return (
        <div className="App">
          <DataContextProvider>
            <Data />
          </DataContextProvider>
        </div>
      );
    };
    
    export default App;
    

    Here is my Data Context code.

    import { createContext, useContext } from "react";
    
    const initialData = {
      type: "chat",
      people: {
        users: [
          {
            name: "Kevin",
          },
          {
            name: "Rebecca",
          },
          {
            name: "Pavlo",
          },
        ],
      },
    };
    
    const dataContext = createContext();
    
    const useData = () => useContext(dataContext);
    
    const DataContextProvider = ({ children }) => {
      return (
        <dataContext.Provider value={initialData}>{children}</dataContext.Provider>
      );
    };
    
    export { DataContextProvider, useData };
    

    Hope this will help.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search