I’m currently learning about useReducer for react. I’m trying to make a recipe box with ingredients, measurements and amounts that you can change by typing inside the text-input boxes. But whenever I try to do the typing, the entire list disappears, and I get this error
react-dom.js:9 TypeError: Cannot read properties of undefined (reading 'ingredients') at App (pen.js:63:26) at Bi (react-dom.js:7:19481) at ei (react-dom.js:9:3150) at oa (react-dom.js:9:44778) at la (react-dom.js:9:39715) at pf (react-dom.js:9:39646) at Ir (react-dom.js:9:39506) at so (react-dom.js:9:36651) at on (react-dom.js:7:3250) at Gi (react-dom.js:9:36960)
Each recipe seems to return “undefined” when I try to change any of the texts. I don’t understand why the recipe parameter works before I type and not afterwards
This is the link to my code https://codepen.io/bl1xvan/pen/eYKmNbm?editors=0010
Advertisement
Answer
You have done a small mistake in the formReducer “CHANGE INGREDIENT” action. In your formReducer
, dispatched action only returns the ingredients as the state. You need to keep the current recipe data and should only change the ingredients.
See the following change in the formReducer
const formReducer = (state, action) => { switch (action.type) { case "CHANGE_INGREDIENT": return state.map((recipe) => { return { ...recipe, ingredients: recipe.ingredients.map((ingredient) => { if (ingredient.id === action.id) { return { ...ingredient, [action.payload.name]: action.payload.value }; } else { return ingredient; } }) }; }); default: return state; } };