Ahmad Bayraktar
Ahmad Bayraktar

Reputation: 5

How to Add Object to Array State in ReactJs?

I have this array of objects state, and it is working fine. I need add another object to it dynamically.

const [productData, SetProductData] = useState({
    sizes: [
        {id: 2, value: 'Small', isActive: false},
        {id: 2, value: 'Medium', isActive: false},
        {id: 2, value: 'Large', isActive: true},
        {id: 2, value: 'X Large', isActive: false},
        {id: 2, value: 'XX Large', isActive: false}
    ]
})

I tried to do it like this, but it is not working

const addObjectToArray = obj => {
    SetProductData(current => [...current, obj]);
};

addObjectToArray( {id: 3, value: 'XXX Large', isActive: true} )

I also need to update it dynamically

Upvotes: 0

Views: 45

Answers (1)

dbuchet
dbuchet

Reputation: 1651

You need to keep the same structure in your state. You had an object, and you're changing it to an array. So


const addObjectToArray = obj => {
  SetProductData(current => ({
    ...current,
    sizes: [...current.sizes, obj]
  }));
};

addObjectToArray( {id: 3, value: 'XXX Large', isActive: true} )

Upvotes: 2

Related Questions