Home > OS >  how to update nested state array and then return the entire array react
how to update nested state array and then return the entire array react

Time:10-12

I'm using React Hooks. This is my state:

const [ chats, setChats ] = useState()

And i have this array in my "chats" state:

[
    {
        "messages": [ //I refer this field
            {
            "message": "hi",
            "seen": false,
            "_id": "61658b533da2d51eace71b31",
            "user": {"user data"}
            }
        ],
        "users": ["some data"],
        "avatar": "data",
        "_id": "61634b62c1a7612f04296335",
        "type": "private"
        },
    {
      "messages": [],
      "users": ["some data"],
      "avatar": "data",
      "_id": "616355d7e124771d98426240",
      "type": "private"
    }
]

So i just need to update the "messages" field from the "0" element of that "chat" array with this newMessage object:

{
  "message": "another hi",
  "seen": false,
  "_id": "61658f551ccbac34a8d10130",
  "user": {"some user data"}
}

I have tried with the most popular answer but it only returns the "messages" field, and i need to return the entire array.

Code:

setChats([...chats[currentlyChatIndex].messages, newMessage])

CodePudding user response:

You can map over the array, and if you are at the currentlyChatIndex you can append the messages field.

Example

const data = [
    {
      "messages": 
      [
          {
            "message": "hi",
            "seen": false,
            "_id": "61658b533da2d51eace71b31",
            "user": "user data"
          }
      ],
      "users": ["some data"],
      "avatar": "data",
      "_id": "61634b62c1a7612f04296335",
      "type": "private"
    },
    {
      "messages": [],
      "users": ["some data"],
      "avatar": "data",
      "_id": "616355d7e124771d98426240",
      "type": "private"
    }
]

const addMessage = (index, message) => {
  return data.map((el, i) => i === index ? {...el, messages: [...el.messages, message]} : el)
}

console.log(addMessage(0, {message: 'another hi'}))

Your case

setChats(chats => chats.map((chat, index) => index === currentlyChatIndex ? 
     { ...chat, messages: [...chat.messages, newMessage] } : chat))
  • Related