I'm using react hooks context to manage state. However, I've run into this issue, where React.useContext() returns undefined even though I'm passing in my context object (or so I think, anyway). Am I missing something really obvious? What's happening?
I have been trying to fetch data from localhost server using usecontext but it is showing undefined. the data is fetched correctly if i fetch it in app.js.
StateContext.js
import React, { createContext, useState, useEffect } from "react";
const StateContext = (props) => {
const StateContext = createContext();
const [data, setData] = useState([]);
const getData = async () => {
let url = "http://localhost:4000/products";
let data = await fetch(url);
let parsedData = await data.json();
setData(parsedData);
};
useEffect(() => {
getData();
}, []);
return (
<StateContext.Provider value={data}>
{props.children}
</StateContext.Provider>
);
};
export default StateContext;
App.js
import './App.css';
import Products from './Products/Products';
function App(props) {
return (
<div>
<Products />
</div>
);
}
export default App;
Product.js
import React, { useContext } from 'react'
import StateContext from '../Context/StateContext'
const Products = () => {
const context = useContext(StateContext)
const data = context
return (
<div>
Products
{console.log(data)}
</div>
)
}
export default Products
CodePudding user response:
When using context
, you need to wrap your app code in the Provider
in order to provide the context to all components.
Context.Provider component available on the context instance is used to provide the context to its child components, no matter how deep they are. ... what's important here is that all the components that'd like later to consume the context have to be wrapped inside the provider component.
https://dmitripavlutin.com/react-context-and-usecontext/
So you should wrap your App.js code in the StateContext
component like this:
function App(props) {
return (
<StateContext>
<div>
<Products />
</div>
</StateContext>
);
}
Edit:
You also forgot to export the StateContext
variable itself.
Your code:
const StateContext = createContext();
Should be:
export const StateContext = createContext();
And when you import the context variable only, you need to import it like this (in Product.js):
import {StateContext} from '../Context/StateContext'
But when you import the entire component that returns the Provider (in App.js)
You need to import it like this (Because this is the default export in the StateContext.js
):
import StateContext from './Context/StateContext'
I would advise you to change to component name to "StateContextProvider" or something so it won't confuse you.