Search code examples
node.jsreactjsreduxreact-reduxredux-thunk

Redux - Find object in state array by its key and update its another key


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

  1. User inputs the title of a post
  2. Title is then sent to dispatch which fetches a POST route in NodeJS and sends title through body
  3. In NodeJS route i am adding a new item in collection with that title

BACKEND DONE, new post is in the server

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

  2. 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:

  1. Clicking on a button on a post triggers a dispatch which fetches NodeJS PUT route
  2. NodeJS route finds the post using ID and adds 1 to the old value of likes the post had

BACKEND DONE, post now has 1 more like in the server

  1. 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

  2. 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


Solution

  • 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.