Problem
using React, I have a meal, which has an array of ingredients
const [meal, setMeal] = useState()
meal = {
foo: ,
bar: ,
ingredients: [
id:
name:
]
}
I also need to edit the ingredients name, so I have a different state to track it. I have used the spread operator on this.
[changeIngredients, setChangeIngredients] = useState();
// in a separate useEffect
setChangeIngredients([...meal.ingredients])
The problem starts when I update changeIngredients
as such
handleEdit = (e) => {
let temp = [...changeIngredients];
temp[e.positionOfArray].name = Number(e.target.value);
setChangeIngredients(temp);
};
I find that meal.ingredients
is also updated, and as such can't do a comparison to see if anything changed.
I previously tried using setChangeIngredients with the response.data from an API call, but the results were the same.
setMeal(response.data)
setChangeIngredients([...response.data.ingredients])
Any advice or suggestions will be appreciated
question from:
https://stackoverflow.com/questions/65879433/i-have-2-states-but-both-are-updating-even-though-i-only-setstate-one-of-them 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…