-1

This is my current data

const [propertyData, setPropertyData] = useState({
    propertyName: '',
    contacts: [
     {
       contactName: 'Person1',
       contactNumber: 'Number1',
     },
     {
       contactName: 'Person2',
       contactNumber: 'Number2',
     },
    ]
})

What I'm trying to achieve is to add another object to contacts like this

contacts: [
     {
       contactName: 'Person1',
       contactNumber: 'Number1',
     },
     {
       contactName: 'Person2',
       contactNumber: 'Number2',
     },
     {
       contactName: 'Person3',
       contactNumber: 'Number3',
     },
    ]

What I'm doing is this

setPropertyData({
  ...propertyData,
  contacts: [{ ...propertyData.contacts, contactPerson: 'Person3', contactNumber: 'Number3', }]
})

But what it does is it's updating the current data with just the new one without the old one like this

contacts: [
     {
       contactName: 'Person3',
       contactNumber: 'Number3',
     },
    ]

I'm kind of always confused using the spread operator especially if it's an array or an object I have to to append to. Please help. Thank you!

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
ayabbear
  • 308
  • 4
  • 20
  • Try `contacts: [...propertyData.contacts, {contactPerson: 'Person3', contactNumber: 'Number3'}]`. – ggorlen Dec 01 '20 at 17:37
  • Does this answer your question? [Push method in React Hooks (useState)?](https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate) – Emile Bergeron Dec 01 '20 at 18:02

2 Answers2

1

You can use this syntax to add a new object to your array of objects :

setPropertyData({
  ...propertyData,
  contacts: [...propertyData.contacts, { contactPerson: 'Person3', contactNumber: 
            'Number3' }]
})
VersifiXion
  • 2,152
  • 5
  • 22
  • 40
0
setPropertyData({
  ...propertyData,
  contacts: [...propertyData.contacts, {contactPerson: 'Person3', contactNumber: 'Number3'}]
})
codemonkey
  • 7,325
  • 5
  • 22
  • 36
Madhuri
  • 1,060
  • 5
  • 17