'How to mutate specific object in an array using SWR

I have the following array

[
{
"idChatPublic": 17,
"idChatRoom": 2,
"idSender": "6c25110d-4256-42e1-8205-b75ece274487",
"username": "Hudson Thadeu Teixeira",
"message": "hello",
"avatar": null,
"createdAt": "12:43",
"chatLike": []
},
{
"idChatPublic": 33,
"idChatRoom": 2,
"idSender": "6c25110d-4256-42e1-8205-b75ece274487",
"username": "Hudson Thadeu Teixeira",
"message": "jam",
"avatar": null,
"createdAt": "13:07",
"chatLike": [
  {
    "idChatLike": 1,
    "idChatPublic": 33,
    "idUser": "",
    "createdAt": "2022-02-14T08:59:34.000Z"
  }
 ]
}
]

How can mutate an specific object of this array and add an object to the "chatLike" array using SWR?

I have the following function:

async function sendLike() {
const newLike = {
  idUser: myUser.userId,
}

mutate(
  async (data) => {
    console.log(data[messageIndex]) // This log returns specific object in the array

    // Handle mutation

  },
  false
)
socket.emit('send_like', newLike)
}

Please guys I've been trying this for a while would be great If someone gives me a hand :D



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source