I am working on a CRUD app using NodeJS in backend and React + Redux in frontend. This is a quick schema of how everything works in it:
Adding an item
POST
route in NodeJS and sends title through bodyBACKEND DONE, new post is in the server
I am adding .then()
on dispatch function in step 2. in which I dispatch an action with type: 'ADD_POST'
and post: post
(i got post from NodeJS res.json({post: result from database})
)
In my reducer i set up a CASE 'ADD_POST': return action.post
FRONTEND DONE, the same post is now visible to user without refreshing
I want to use the same logic to update the likes of a specific post. This is what I've done so far:
PUT
routeBACKEND DONE, post now has 1 more like in the server
I am adding .then
again to the dispatch which fetches NodeJS route in which I dispatch an action with type 'ADD_LIKE'
and post ID
that I updated
in reducer I set up a CASE 'ADD_LIKE':
which iterates through the state using the code in the following snippet.
Here's that snippet:
state.map(item => {
if(item.id === action.postid) {
//i find the specific item, but now im stuck on how to update the likes property of it
}
})
If it helps, this is the playlist I've been watching, if you want to you can see how this guy implements Delete function, I want to add Likes function using the same logic: Link to playlist
state.map(item => {
if (item.id !== action.postid) return item; // no need to change other items
const likes = item.likes;
return Object.assign({}, item, {likes: likes + 1}); // [1]
});
Line [1]
creates a new object with all the same properties of item
, but it overwrites the existing property likes
and simply adds 1
.
Make sure you actually create a new object for the changed item in the reducer, as everything in your state should be immutable.