react context is giving undefined object

Tags: , , ,



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.

ImgContext.js

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}

ImageGrid.js

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;

Answer

You are not providing a a 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({});


Source: stackoverflow