Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update a specific objects values in an array of objects redux

My goal is to update the animatedPhotoUrl value for chatId #1 (or the first object in the chats array.

const chats = [

  {"admin": "590", 
  "animatedPhotoUrl": "", 
  "chatId": "1"}, 

  {"admin": "680", 
   "animatedPhotoUrl": "", 
   "chatId": "2"},
  {"admin": "420", 
   "animatedPhotoUrl": "", 
   "chatId": "2"}

]

However, when I console.log(chats) after I update in the reducer, I get the error:

[undefined, undefined]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my dispatch:

dispatch({
          type: "UPDATE_CHAT_PROFILE_PICTURE_URL",
          payload: {
            profilePictureUrl: res.imageUrl,
            animatedPhotoUrl: "",
            chatId: chat.chatId,
          },
        });

And here is the code in my reducer:

 case "UPDATE_CHAT_PROFILE_PICTURE_URL":
      return {
        ...state,
        chats: state.chats.map((chat) => {
          chat.chatId === action.payload.chatId
            ? {
                ...chat,
                animatedPhotoUrl: action.payload.animatedPhotoUrl,
              }
            : chat;
        }),
      };

>Solution :

You need to add return here:

chats: state.chats.map((chat) => {
  return chat.chatId === action.payload.chatId
    ? {
        ...chat,
        animatedPhotoUrl: action.payload.animatedPhotoUrl,
      }
    : chat;
}),

or you need to drop braces to get implicit return:

chats: state.chats.map((chat) => 
  chat.chatId === action.payload.chatId
    ? {
        ...chat,
        animatedPhotoUrl: action.payload.animatedPhotoUrl,
      }
    : chat;
),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading