1

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])
2
  • I use immutable-js for list, it would create a whole new object and make react to update Commented Oct 12, 2021 at 13:53
  • Updating more complex data structures like this, is more suited to useReducer than useState. See the react docs, if you've used Redux before it'll be familiar. Commented Oct 12, 2021 at 13:55

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

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.