In my react application I am trying to use context api. In my component I am importing the context but it is giving error that object can not destructure the property. I am trying to implement cart functionality in my app. I am using hooks.
import React, { createContext, useState } from 'react';
const ImgContext = createContext();
const ImgConProvider = ({children}) => {
const [myCart, setMyCart] = useState([]);
return(
<ImgContext.Provider value={{myCart, setMyCart}}>
{children}
</ImgContext.Provider>
)
}
export {ImgContext, ImgConProvider}
import React, { useContext, useState } from 'react';
import ImageGrid from './ImageGrid';
import { ImgContext } from './Context/ImageContext';
const Home = () => {
const { myCart } = useContext(ImgContext);
return (
<div className="App">
{myCart}
</div>
)
}
export default Home;
You are not providing aa default value when creating the context. If there is a scenario where the component doenst have access to a provider the value from context would be undefined which maybe causing the issue. Better provide a default value.
const ImgContext = createContext({});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.