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