0

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

1 Answer 1

2

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} )

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. You can flag the answer as correct :)

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.