I am fairly new to React Hooks and context api. I am trying to create a global state management within react (no redux) but I am running into this error.
TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
I just started this project and just trying to set up a shopping cart (which will use the global CartItem to keep track of total items)
GlobalStates.jsx (My global state manager file)
import React from 'react';
export const CartContext = React.createContext(0)
const GlobalContextWrapper = (props) => {
const [cartItem,incCartItem] = React.useState(0);
return(
<CartContext.Provider value={[cartItem,incCartItem]}>
{props.children}
</CartContext.Provider>
)
}
export default GlobalContextWrapper
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import GlobalContextWrapper from "./GlobalStates.jsx"
import Test from "./Test.jsx"
const Main = () => {
return(
<GlobalContextWrapper>
<Test/>
</GlobalContextWrapper>
)
}
ReactDOM.render(<Main/>,document.getElementById('root'));
Test.jsx (the file which is trying to access the context global states)
import React from 'react';
import CartContext from "./GlobalStates"
const Test = () => {
const [cartItem,incCartItem] = React.useContext(CartContext)
return(
<h1>The cart total is {cartItem}</h1>
)
}
export default Test
Your code works just fine, but in Test you need to import the context correctly: import {CartContext} from "./GlobalStates"
const CartContext = React.createContext(0); const GlobalContextWrapper = (props) => { const [cartItem, incCartItem] = React.useState(0); return ( <CartContext.Provider value={[cartItem, incCartItem]}> {props.children} </CartContext.Provider> ); }; const Test = () => { const [cartItem, incCartItem] = React.useContext( CartContext ); return <h1>The cart total is {cartItem}</h1>; }; const Main = () => { return ( <GlobalContextWrapper> <Test /> </GlobalContextWrapper> ); }; ReactDOM.render(<Main />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
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.