I have an object in react with each key consisting of different arrays. I want to add new values to the desired array without mutating the previous elements. I need to be able to change the target key with a variable.
const desiredCuisine = ?????
const valueToAdd = "Pizza"
const [cuisines, setCuisines] = useState({
french: [],
italian: [],
german: []
})
const handleClick = (desiredTargetKey) => {
setCuisines((prev) => ({
...prev,
desiredTargetKey: [...adToPublish.desiredTargetKey, valueToAdd],
}))
}
CodePudding user response:
You could use it like this
setCuisines((prev) => ({
...prev,
[desiredTargetKey]: [...prev[desiredTargetKey], valueToAdd],
})
);