const [mealData, setMealData] = useState({ title: '', description: '', category: '', price: '', mealIMG: null, ingredients: [], })Así que tengo este objeto de estado en mi componente. Cuando hago clic en el botón Agregar, el estado se vuelve así: (digamos que hicimos clic dos veces)
{ title: '', description: '', category: '', price: '', mealIMG: null, ingredients: [ {ingredient:"", qty:"", unit:"", id:id}, {ingredient:"", qty:"", unit:"", id:id}, ], }Ahora, en el controlador de eventos de cambio, quiero actualizar el estado sin mutar el otro. Estoy usando esta función para lograr el trabajo, pero no funciona:
const handleIngredients = (e, index) => { const { name } = e.target setMealData((prev) => { return { ...prev, ingredients: [ { ...prev.ingredients[index], [name]: e.target.value, }, ], } }) }¿Alguna pista, por favor?
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>