2

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

1 Answer 1

3

Use bracket notation:

setFoodArray((prev) => {
    return update(prev, {[index]: {amount: {$apply: function(x) {return x -1}}}})
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.