Desde la interfaz de usuario a continuación, quiero generar algo como esto en mi estado.
[{title: 'Barnes Chapman', options:{extra large: '8.0', ketchup: '1.00', extra tomato: '2' } }]
Creé una función pero la función no funciona correctamente, el estado solo se actualiza 2 veces cuando quiero actualizar el estado la tercera vez que no se actualiza, he depurado y las condiciones funcionan pero el valor anterior no se almacena y La tercera vez que el estado ya no se actualiza.
const getIngredients = (e, product) => { setIngredients((prevValue) => { const isExist = prevValue.find((item) => item.title === product.title); console.log(isExist); console.log({ ...isExist?.options, title: e.target.name, price: e.target.value, }); if (isExist) { isExist.options = { // Problem is here previous value is not storing ...isExist.options, title: e.target.name, price: e.target.value, }; return prevValue; } return [ ...prevValue, { title: product.title, options: { title: e.target.name, price: e.target.value }, }, ]; }); };
Código JSX: los valores de las casillas de verificación son dinámicos
{product.ingredients.map((ingredient) => { return ( <li onChange={(e) => getItemValues(e.target, product)}> <label className="container_check"> {ingredient.title} // "ketchup" <span>+ $2</span> <input type="checkbox" value={ingredient.price} // "1" name={ingredient.title} // "ketchup" /> <span className="checkmark"></span> </label> </li> ); })}