I need to add or subtract a value of a element in object array using Immutability helper
const selectedFood= [
{id: uuidv4(), name: "pizza", price: 1700, amount: 3},
{id: uuidv4(), name: "cheese", price: 600, amount: 10},
{id: uuidv4(), name: "fried rice", price: 500, amount: 4},
{id: uuidv4(), name: "coke", price: 100, amount: 5}]
const [foodArray, setFoodArray] = useState(selectedFood);
This code works flawlessly and this is what i want except the index
setFoodArray((prev) => {
return update(prev, {2: {amount: {$apply: function(x) {return x -1}}}})
})
the number 2 here should be the index
so i used this to get the index
const index = foodArray.indexOf(foodArray.find((single) => {
return single.id === id
}));
putting this index variable there dosn't work
setFoodArray((prev) => {
return update(prev, {index: {amount: {$apply: function(x) {return x -1}}}})
})
Picture for understanding better
can anyone help
Use bracket notation:
setFoodArray((prev) => {
return update(prev, {[index]: {amount: {$apply: function(x) {return x -1}}}})
})