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
JavaScript
x
35
35
1
const WeatherContext = React.createContext();
2
3
class WeatherProvider extends Component {
4
state = {
5
query: "",
6
weather: {},
7
details: {},
8
mean: "",
9
mode: "",
10
};
11
12
//my functions here
13
14
render() {
15
return (
16
<WeatherContext.Provider
17
value={{
18
this.state,
19
search: this.search,
20
meanValue: this.meanValue,
21
ModeValue: this.modeValue,
22
}}
23
>
24
{this.props.children}
25
</WeatherContext.Provider>
26
);
27
}
28
}
29
30
const WeatherConsumer = WeatherContext.Consumer;
31
32
export { WeatherConsumer, WeatherContext };
33
34
export default WeatherProvider;
35
App.js
JavaScript
1
40
40
1
import React, { useContext } from "react";
2
3
import WeatherContext from "./context/MyContext";
4
5
import Cards from "./components/Cards";
6
import Header from "./components/Header";
7
import CurrentWeather from "./components/CurrentWeather";
8
import Footer from "./components/Footer";
9
import Summary from "./components/Summary";
10
11
const App = () => {
12
const { weather, details } = useContext(WeatherContext);
13
14
return (
15
<div
16
className={
17
typeof details.current != "undefined"
18
? weather.list[0].main.temp > 15
19
? "app warm"
20
: "app cold"
21
: "app"
22
}
23
>
24
<main>
25
<Header />
26
{typeof details.current != "undefined" && (
27
<>
28
<CurrentWeather />
29
<Cards />
30
<Summary />
31
<Footer />
32
</>
33
)}
34
</main>
35
</div>
36
);
37
}
38
39
export default App;
40
Everything is wrapped in index.js.
Index.js
JavaScript
1
18
18
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
import './index.css';
4
import App from './App';
5
import * as serviceWorker from './serviceWorker';
6
import WeatherProvider from "./context/MyContext"
7
8
9
10
ReactDOM.render(
11
<WeatherProvider>
12
<App />
13
</WeatherProvider>,
14
document.getElementById('root')
15
);
16
17
serviceWorker.unregister();
18
Advertisement
Answer
I think you are not importing your context correctly at:
JavaScript
1
2
1
import WeatherContext from "./context/MyContext";
2
You exported as named in its module, so you need to import it like below:
JavaScript
1
2
1
import { WeatherContext } from "./context/MyContext";
2
at app.js
file