1

this is my reducer

let initialState = [
  { name: 'john', messages: [{ message: "hi" }] },
  { name: 'max', messages: [{ message: "howdy" }] },
  { name: 'alex', messages: [{ message: "hello" }] },
  ...
];

const Messages = (state = [], action) => {
  switch (action.type) {
    case "MESSAGES":
      return [...state, ...action.payload];
    case "UPDATE_ALEX_MESSAGES":
      // HOW TO UPDATE????
    default:
      return state;
  }
};

export default Messages;

how to update alex's messages and push another object to it? (commented part of the above code)

Note: alex's position is not stable and it may change. so something like state[2] is not what I'm looking for. Something more like state.find(x => x.name === 'alex') is more like it..

0

2 Answers 2

1

The map() method and the spread syntax can help you achieve the desired result.

Using the map() method, iterate over the state array and inside the callback function, check if the current user object's name is "alex", if it is, update the current object's messages property by assigning a new array to it and using the spread syntax to copy the existing messages and then also add the new message in the array.

case "UPDATE_ALEX_MESSAGES":
  return state.map((user) => {
      if (name === "alex") {
         user.messages = [...user.messages, newMessage];
      }

      return user;
  });

You could also avoid mutating the existing object by returning a new object inside the if block.

case "UPDATE_ALEX_MESSAGES":
  return state.map((user) => {
      if (name === "alex") {
         return { ...user, messages: [...user.messages, newMessage] };
      }

      return user;
  });

Ideally, you would pass the name of the user in the payload of the action, so the following condition

if (name === "alex") { .. }

will become

if (name === action.payload) { .. }
Sign up to request clarification or add additional context in comments.

Comments

0

I have used this npm package to solve this problem https://www.npmjs.com/package/immer. It is a super useful tool that helps reduce boilerplate code

Comments

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.