I have the following array of objects:
[{
idChatPublic: "1",
message: "hello",
chatLike: [{
id: "1",
idChatPublic: "1"
}]
}]
What I want is simply add a new object into chatLike array. Here is my attempt, but it doesn't seem to be working whats wrong with this piece of code?
async function sendLike(messageId: string) {
const newLike = {
idChatPublic: messageId,
}
mutateMessages(
(data) => {
console.log(data) // returns the array I want to update
data.map((message) => {
if (message.idChatPublic === messageId) {
console.log(message.chatLike) // returns the array inside the object I want to update
return {
...message,
chatLike: [...message.chatLike, newLike]
}
} else {
return message
}
})
}
)
}
CodePudding user response:
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Probably, you have to create const with new array and return it:
const newData = data.map((message) => {
if (message.idChatPublic === messageId) {
console.log(message.chatLike) // returns the array inside the object I want to update
return {
...message,
chatLike: [...message.chatLike, newLike]
}
} else {
return message
}
});
return newData;
CodePudding user response:
const data = [
{
idChatPublic: "1",
message: "hello",
chatLike: [
{
id: "1",
idChatPublic: "1",
},
],
},
];
function updateChatLike() {
return data.map((d) => {
return {
...d,
chatLike: [
...d.chatLike,
{
id: 2,
idChatPublic: "2",
},
],
};
});
}
console.log(JSON.stringify(updateChatLike(), null, 4));
I have used JSON.stringify() to log complete nested object
Output
[
{
"idChatPublic": "1",
"message": "hello",
"chatLike": [
{
"id": "1",
"idChatPublic": "1"
},
{
"id": 2,
"idChatPublic": "2"
}
]
}
]
CodePudding user response:
You don't need map()
. I think you can do that like this:
async function sendLike(messageId: string) {
const newLike = {
idChatPublic: messageId,
};
mutateMessages((data) => {
data.forEach((message) => {
if (message.idChatPublic === messageId) {
message.chatLike.push(newLike);
}
}
});
}
Loop throw your objects array with forEach()
and if the id will match you can update chatLike
array with push()
to add a new newLike
object.
CodePudding user response:
Map is not necessary here in your case.
Try this.
const data = [{
idChatPublic: "1",
message: "hello",
chatLike: [{
id: "1",
idChatPublic: "1"
}]
}];
console.log("before " , data);
sendLike(1);
console.log("after " , data);
function sendLike(messageId) {
const newLike = {
idChatPublic: messageId,
}
// mutateMessages((data) => {
data.forEach((message) => {
//console.log(message.idChatPublic);
if (message.idChatPublic == messageId) {
message.chatLike.push(newLike);
}
});
//});
}