Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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 })))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading