matharoo

Categories

  • reactjs

Tags

  • js
  • reactjs

For this post I will be going over on updating state object like with the help of useState hook in functional components of ReactJS:

const [device,setDevices] = useState({'name':'iphone 6S','os':''});

The state object already has value for property defined. Now we want to update the property os to iOS 12 while preserving the state of name property. Here’s how to do it:

const field = 'os'
setDevices(prevState => {
    return { ...prevState, [field]: 'iOS 12' }
});

What if we have a list/array of objects in our device state like:

[
  {
  'name':'samsung s10',
  'os':''
  },
  {
  'name':'iphone 6S',
  'os':''
  },
  {
  'name':'Blackberry',
  'os':''
  }
]

Now before we update we need to do a quick lookup, here’s how we update the state when we find the item we want to update:

const update={'name':'iphone 6S','os':'iOS 12'}
setDevices(device.map(function (item) {
    if (item.name !== update.name) return item;
    return update;
}))

That is it. Your state is now updated. This can be useful when we are updating list of objects and performing CRUD operations on the list while updating the db in the backend. Enjoy!