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])
useReducerthanuseState. See the react docs, if you've used Redux before it'll be familiar.