Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
How to handle nested elements in hooks?
const [mealData, setMealData] = useState({
title: '',
description: '',
category: '',
price: '',
mealIMG: null,
ingredients: [],
})

So i have this state object in my component. When i click on add button the state becomes like this: (let's say we clicked twice)

{
title: '',
description: '',
category: '',
price: '',
mealIMG: null,
ingredients: [
        {ingredient:"", qty:"", unit:"", id:id},
        {ingredient:"", qty:"", unit:"", id:id},
  ],
}

Now on the change event handler i want to update the state without mutating the other i am using this function to achieve the work but it's not working:

const handleIngredients = (e, index) => {
  const { name } = e.target
  setMealData((prev) => {
    return {
      ...prev,
      ingredients: [
        {
          ...prev.ingredients[index],
          [name]: e.target.value,
        },
      ],
    }
  })
}

Any clue please?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

const { useEffect, useState } = React;

function Example() {

  const [ state, setState ] = useState({
    title: '',
    description: '',
    category: '',
    price: '',
    mealIMG: null,
    ingredients: []
  });

  useEffect(() => {
    const json = JSON.stringify(state.ingredients);
    console.log(json);
  }, [state]);

  function handleChange(e) {
    
    // Grab our needed props from the
    // changed input
    const {
      name,
      value,
      parentNode: { id },
    } = e.target;

    // Get ingredients from state
    const { ingredients } = state;

    // Is there is an object in the ingredients
    // where the id matches the id from the props
    const found = ingredients.find(i => {
      return i.id === id;
    });

    // If there is...
    if (found) {
      
      // Create a new object using the found
      // object, and the name/value of the input
      const updated = { ...found, [name]: value };
      
      // `filter` out all the objects where the object id
      // doesn't match the id from props
      const filtered = ingredients.filter(i => {
        return i.id !== id
      });
      
      // Set the new state using the filtered
      // array, and the updated object
      setState({
        ...state,
       ingredients: [ ...filtered, updated ]
      });
    
    // If an object isn't found
    } else {

      // Add a new object to the ingredients array
      setState({
        ...state,
        ingredients: [
          ...state.ingredients,
          { id, [name]: e.target.value }
        ]
      });

    }

  }

  return (
    <div>
      <Input id="1" handleChange={handleChange} />
      <Input id="2" handleChange={handleChange} />
    </div>
  );

};

function Input({ id, handleChange }) {
  return (
    <div className="set" id={id} onChange={handleChange}>
      Ingredient: <input name="ingredient" />
      Qty: <input name="qty" />
      Unit: <input name="unit" />
    </div>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
input { display: block; } 
.set { display: inline-block; margin-bottom: 1em; border: 1px solid #454545; padding: 0.2em; width: 45%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda