Add or Remove element from array in nested Object in React hooks

Viewed 20

In this below example, I want add or remove the products array elements from object3 and need to updated in react hooks state. I have tried with filter method inside setter for deleting an element but it won't work. can anyone pls help to do with efficiently.

const myValue = {
                object1: {},
                object2: {},
                object3: {
                    products: [{
                        name: 'Fruits',
                        id: '1'
                    },
                    {
                        name: "Vegtables",
                        id: '2'
                    }],
                    number: 1
                }
            }

  
1 Answers

You can extract out the object3 as another variable, do whatever operations you want to do and set state again combining it with the current state value.

const {object3} = myValue;

// for example if you want to filter based on condition for id
const modifiedProducts = object3.products.filter((item) => item.id > '1');

setMyValue({
    ...myValue, 
    object3: {
        ...object3, 
        products: modifiedProducts
    }
})

I would also suggest making multiple states for each object if all objects are independent from each other. Here if some component only depends on object1, ideally it should not re render when object 3 updates.

Related