Skip to content
Advertisement

Context API problem – object is undefined

I’ve been always using Redux, but I finally decided to try to play with Context API, but apparently I’m missing something. I get an error “TypeError: Object(…)(…) is undefined” in App.js, weather and details appear to be undefined.

Could you please check out my code in order to help me out in finding a mistake? I thought I should have a direct access to the state without the need of destructuring. Or maybe destructuring is the only way to go?

Here you can see all parts of my code – context + wrapped app.js.

MyContext.js

const WeatherContext = React.createContext();

class WeatherProvider extends Component {
  state = {
    query: "",
    weather: {},
    details: {},
    mean: "",
    mode: "",
  };

  //my functions here

  render() {
    return (
      <WeatherContext.Provider
        value={{
          ...this.state,
          search: this.search,
          meanValue: this.meanValue,
          ModeValue: this.modeValue,
        }}
      >
        {this.props.children}
      </WeatherContext.Provider>
    );
  }
}

const WeatherConsumer = WeatherContext.Consumer;

export { WeatherConsumer, WeatherContext };

export default WeatherProvider;

App.js

import React, { useContext } from "react";

import WeatherContext from "./context/MyContext";

import Cards from "./components/Cards";
import Header from "./components/Header";
import CurrentWeather from "./components/CurrentWeather";
import Footer from "./components/Footer";
import Summary from "./components/Summary";

const App = () => {
  const { weather, details } = useContext(WeatherContext);

  return (
    <div
      className={
        typeof details.current != "undefined"
          ? weather.list[0].main.temp > 15
            ? "app warm"
            : "app cold"
          : "app"
      }
    >
      <main>
        <Header />
        {typeof details.current != "undefined" && (
          <>
            <CurrentWeather />
            <Cards />
            <Summary />
            <Footer />
          </>
        )}
      </main>
    </div>
  );
}

export default App;

Everything is wrapped in index.js.

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import WeatherProvider from "./context/MyContext"



ReactDOM.render(
  <WeatherProvider>
    <App />
  </WeatherProvider>,
  document.getElementById('root')
);

serviceWorker.unregister();

Advertisement

Answer

I think you are not importing your context correctly at:

import WeatherContext from "./context/MyContext";

You exported as named in its module, so you need to import it like below:

import { WeatherContext } from "./context/MyContext";

at app.js file

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement