I am learning to use useContext and useReducer together but am getting an error I haven't managed to figure out:
Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
It occurred after destructuring the context inside MealItemForm.js. I tried setting default value in createContext, importing with and without curly braces etc. I am trying to dispatch the function inside children component. Any idea?
MealItemForm.js
import React,{useContext} from 'react';
import MeatContext from '../store/meat-context';
import Input from './Input';
import styles from "./MealItemForm.module.css"
function MealItemForm(props) {
const [meatState,dispatchMeatState]=useContext(MeatContext)
const handleClick=(event)=>{
event.preventDefault();
}
return (
<form className={styles.form}>
<Input/>
<button onClick={handleClick}>+ Add</button>
</form>
);
}
export default MealItemForm;
meat-context.js
import React,{useReducer,useState} from 'react';
const MeatContext = React.createContext({meatState:[]});
export function MeatContextProvider(props) {
const meatReducer = (state, action) => {
if (action.type === 'ADD_MEAT') {
return [...meatState];
}
return { };
};
const [meatState, dispatchMeatState] = useReducer(meatReducer,
[
]
);
return (
<MeatContext.Provider value={{meatState:meatState,dispatchMeatState:dispatchMeatState}}>
{props.children}
</MeatContext.Provider>
);
}
export default MeatContext
The value provided to Context
is an object
{meatState:meatState,dispatchMeatState:dispatchMeatState}
But you're using array destructuring while getting the values
const [meatState, dispatchMeatState ] = useContext(MeatContext)
Using object destructuring should solve it,
const { meatState, dispatchMeatState } = useContext(MeatContext)