Home > OS >  Update a specific objects values in an array of objects redux
Update a specific objects values in an array of objects redux

Time:01-03

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]

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;
        }),
      };

CodePudding user response:

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;
),
  • Related