-1

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)

1

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

thanks! but I've used condition in fetching Data function to get data response.data ? setWeatherReport(response.data) :setWeatherReport([])
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.