Home > front end >  How to switch between object keys and clone the previous values before adding new values in react
How to switch between object keys and clone the previous values before adding new values in react

Time:10-15

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],
    })
 );
  • Related