Home > Mobile >  Context provider returns undefined in React
Context provider returns undefined in React

Time:09-04

I am new in react, and trying to create a shopping website. I wanted to create a global array to save the products in cart. However, I encountered with an error "TypeError: Cannot read properties of undefined (reading 'includes')" when I tried to add an item to the cart array. I thought that it is because the context provider provides an undefined, seeing on the log the value of cart "undefined".

My codes for Context:

const AppContext = React.createContext("")

export const AppProvider = ({
    children
}) => {
    const [cart, setCart] = useState([])

    const value = { cart, setCart }

    return <IconContext.Provider value={value}>{children}</IconContext.Provider>
}

export function useAppContext() {
    return useContext(AppContext)
}

My codes for adding component:

    const { cart, setCart } = useAppContext()

    const handleCartButton = () => {
        if(!cart.includes({item}))
        {
            const newList = cart.concat( [{item}] );
            setCart(newList);
        }
    }
    useEffect(()=>{
        console.log(cart);    
    },[cart])

Codes for index.js:

ReactDOM.render(
  <React.StrictMode>
    <AppProvider>    <App/></AppProvider>

  </React.StrictMode>,
  document.getElementById('root')
);

CodePudding user response:

The problem is you're using a context called AppContext but you're passing props by using IconContext which is not existed in the code above.

  • Related