PYG
PYG

Reputation: 347

Updating all objects in array with UseState in React

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.

Upvotes: 0

Views: 29

Answers (1)

Jakub Kotrs
Jakub Kotrs

Reputation: 6229

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

Upvotes: 3

Related Questions