Home > Back-end >  Updating all objects in array with UseState in React
Updating all objects in array with UseState in React

Time:04-02

What am I doing wrong here?

I'm starting with this:

const [notificationList, setNotificationList] = useState([]);

The array is then populated. Afterwards I want to update every single object in that array... but not working.

setNotificationList(notificationList.map(notif => { ...notif, isRead: true }))

I think it's obvious but I need to sleep.

CodePudding user response:

You have a syntax error. If you run the code, you should see it in the console.

// this is the usual "old" syntax
function() {
  return true
}
// this is the es6 arrow function
() => {
  return true
}
// this is the es6 arrow function without braces
() => true

As you can see here, you can omit {} in an arrow function. However, if you want to return an object, you have to be explicit otherwise the engine doesn't understand_

// not what you want
() => { key: 'value' }
// what you want
() => ({ key: 'value' })

solution:

setNotificationList(notificationList.map(notif => ({ ...notif, isRead: true })))
  • Related