Jeff Goes
Jeff Goes

Reputation: 555

How do I return a redux state with a incremented or decremented value?

I am trying to return a state in redux that just increments/decrements a value.

The variable I am trying to increment looks like this:

state = {
     posts = [
        {title: 'bla', id: '123', value: 1},
        {title: 'bla2' , id: '321' value: 2},
        {title: 'bla3', id: '135' value: 3}
     ]
}

from the actions I dispatch I have the ID of the object I want to increment. So this is what I tried:

state.map(post => {
        if(post.id === action.id){
          let newCount = post.value - 1;
          return {
            ...post,
            value: newCount
          }
        }
      })

But it's not working and I am not sure how to solve this.


Just so you all know, I just had to return it an use and else statement to return the post if I could not find the id.

looks like this:

return state.map(post => {
        if(post.id === action.parentId){
          let newCount = post.commentCount - 1;
          return {
            ...post,
            commentCount: newCount
          }
        }
        else{
          return post;
        }

Upvotes: 0

Views: 144

Answers (3)

jsdeveloper
jsdeveloper

Reputation: 4045

You need to map the posts and then return the new state object like this:

case UPDATE_POST_COUNT:
  let updatedPosts = state.posts.map(post => {
        if(post.id === action.id){
          let newCount = post.value - 1;
          return {
            ...post,
            value: newCount
          }
        } 
        return post; // handle this case too
      })
   // now construct the new state object
   return Object.assign({}, state, {posts: updatedPosts})

Upvotes: 0

Giorgi Moniava
Giorgi Moniava

Reputation: 28674

Does this fix the issue?

let result = state.posts.map(post => {
        if(post.id === action.id){
          let newCount = post.value - 1;
          return {
            ...post,
            value: newCount
          }
        } 
        return post; // handle this case too
      })

This will correctly update the element with given id in state in immutable way - so you need to assign the result to something and use it later as in above code.

Upvotes: 2

Try:

state.posts.map(post => {

instead of:

state.map(post => {

Because you must iterate on the posts Array instead of the state Object

Upvotes: 0

Related Questions