0

i want to replace an object inside an array of object using id to find it, the payload has the new object

const initialState = {
  allComments: []
};

case LIKE_COMMENT:
      let index = state.allComments.findIndex(
        value => value._id === payload._id
      );
      if (index === -1) {
        return {
          ...state,
          allComments: [...state.allComments, ...payload]
        };
      } else {
        return {
          ...state,
          allComments: [
            (state.allComments[index] = payload),
            ...state.allComments
          ]
        };
      }

them problem that it keep pushing that object without replacing the previous one

3 Answers 3

2
 case LIKE_COMMENT:
      return {
        ...state,
        allComments: state.allComments.map(comment => {
          if (comment.id === payload._id) return payload;
          return comment;
        })
      }

this will replace comment with payload and return all other comments

Sign up to request clarification or add additional context in comments.

Comments

1

I think you actually need to define a new array based on your old one before returning it into your state:

... else {
  newComments = state.allComments
  newComments[index] = payload
  return {
    ...state,
    newComments
  };
}

Comments

1

You can use map to create a shallow copy of the allComments array where the matching index is replaced by the payload:

case LIKE_COMMENT:
    return {
      ...state,
      allComments: state.allComments.map(c => c._id === payload._id ? payload : c)
    };

2 Comments

thank you i get it , i thought if i did replace that index i can use it right away .
allComments: [ (state.allComments[index] = payload), ...state.allComments ] replaces the object at the specified index but it also adds the payload object as the first item of the array. It is interpreted as [ payload, ...allComments ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.