I'm using React.memo on a message component for a chat app I am making and am having difficulty with it actually updating when needed.
My message component has an element that states its position (whether it's the first, middle, last of a group or on its own) and that changes when a new message is sent for the previous last message. Also, the message component is being used in a flatlist which may be what's complicating this.
Here is the function I am using to compare the messages to their older versions.
function messagePropsAreEqual(prevMessage, nextMessage) {
if (prevMessage?.messageItem?.message?.messageBody == "ABC") {
console.log(
"Prev",
prevMessage?.messageItem?.message?.messageBody,
prevMessage?.messageItem?.position
);
console.log(
"Next",
nextMessage?.messageItem?.message?.messageBody,
nextMessage?.messageItem?.position
);
}
return (
prevMessage?.messageItem?.message?.id ===
nextMessage?.messageItem?.message?.id &&
prevMessage?.messageItem.position === nextMessage?.messageItem.position
);
}
Right now I have it printing the response when I text ABC and what comes up is:
Prev ABC groupEnd
Next ABC groupEnd
this makes sense to me because when I text it the first time it is assigned groupEnd and there is only one version so I assume prev and next are the same.
Now, when I text another message and the ABC message's position is changed from groupEnd to groupMiddle I expect:
Prev ABC groupEnd
Next ABC groupMiddle
However, what I'm getting is this
Prev ABC groupMiddle
Next ABC groupMiddle
Prev ABC groupMiddle
Next ABC groupMiddle
Here is the code for updated the flatlist:
const addMessage = (
msg:
| {
id: string;
imageUrl: string;
chatuserID: string;
imageWidth: number;
imageHeight: number;
}
| MessageModel
) => {
if (msg && chat != undefined && currentChatUser != undefined) {
const isNotOfGroup =
messages.length === 0 ||
currentChatUser?.id != messages[0].message.chatuserID;
const newMessage = {
message: msg,
position: isNotOfGroup ? "notOfGroup" : "groupEnd",
chat: chat,
currentChatUser: currentChatUser,
isLocal: true,
};
var existingMessages = [newMessage, ...updateLastMessagePosition()];
setMessages(existingMessages);
}
};
const updateLastMessagePosition = () => {
var existingMessages = [...messages];
const lastMessage = messages[0];
if (lastMessage != null) {
if (lastMessage.message.chatuserID == currentChatUser?.id) {
if (lastMessage.position == "notOfGroup") {
existingMessages[0].position = "groupStart";
} else {
existingMessages[0].position = "groupMiddle";
}
}
}
return existingMessages;
};
I would be grateful for any help!