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 state data containing a nested array of objects

My state "data" consist of the following nested array of objects

{
    "message": "Fetched films successfully.",
    "films": [
        {
            "_id": "640685ea5d0f00f7f2e4c5b5",
            "title": "Catwoman: Hunted",
            "imageUrl": "images/5.png",
            "releaseDate": "2023-03-16T04:00:00.000Z",
            "reviewcnt": 4,
            "reviewavg": 3,
            "userlikecnt": 3
        },
        {
            "_id": "640685f05d0f00f7f2e4c5bf",
            "title": "Troll",
            "imageUrl": "images/1.jpg",
            "releaseDate": "2023-01-23T04:00:00.000Z",

I’m trying to decrement the userlikecnt of filmID : 640685ea5d0f00f7f2e4c5b5 as follows:

setData(prevState=>{
    prevState.films.map(film=>{
        if(film._id===id)
            return{
                ...film,
                userlikecnt:film.userlikecnt-1,
            }
            return film;
        })
    })

Where id containts "640685ea5d0f00f7f2e4c5b5". The above code isn’t 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

>Solution :

It looks like you are not returning the modified state after mapping over the films array. You can modify your code:

setData(prevState => {
  return {
    ...prevState,
    films: prevState.films.map(film => {
      if (film._id === id) {
        return {
          ...film,
          userlikecnt: film.userlikecnt - 1
        };
      }
      return film;
    })
  };
});
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