Ad

Why Won't My Controlled Input Component In React Update With The State?

- 1 answer

I've got a list of ingredients in an "editIngreds" array in my state, e.g. ['Apple', 'Banana', 'Orange']. They are rendered to the DOM via react map function. I have an edit mode that replaces the text with Input boxes so I can edit the items and save them back to the state array. However, when typing in the box, nothing happens. console.log shows that editIngreds[i] is indeed being updated when I type a character, however the input boxes do not update with this new value.

 export default function RecipeCard({ recipe, onEditRecipe, onRemoveRecipe }) {
      const ingredients = Object.values(recipe.ingredients);
      const ingredientKeys = Object.keys(recipe.ingredients);

      const [editIngreds, setEditIngreds] = React.useState(ingredients)

      ...

      const onChangeEditIngreds = (event, i) => {
        const value = event.target.value;
        const ingreds = editIngreds
        ingreds[i] = value;
        setEditIngreds(ingreds);
      };

      ...

      return (
        <ul>
          {ingredients.map((ingred, i) => (
            <li key={ingredientKeys[i]}>
              {editMode ? (
                <Input
                  type="text"
                  value={editIngreds[i]}
                  onChange={(e) => onChangeEditIngreds(e,i)}
                />
               ) : (
                 <>{ingred}</>
               )}
             </li>
           ))}
         </ul>
Ad

Answer

You are mutating the state. Make a shallow copy of ingredients before updating

const onChangeEditIngreds = (event, i) => {
    const value = event.target.value;
    const ingreds = [...editIngreds];
    ingreds[i] = value;
    setEditIngreds(ingreds);
  };
Ad
source: stackoverflow.com
Ad