I want to add a pagination to my app for this reason i coded below code but there is a problem.
Here is my useEffect:
useEffect(() => {
let x = null;
const unsubscribe = chatsRef
.orderBy("createdAt", "desc")
.limit(10)
.onSnapshot((querySnapshot) => {
const messagesFirestore = querySnapshot
.docChanges()
.filter(({ type }) => type === "added")
.map(({ doc }) => {
const message = doc.data();
x = message;
return { ...message, createdAt: message.createdAt.toDate() };
});
appendMessages(messagesFirestore);
if (latestMessage != null) {
if (
new Date(
latestMessage["createdAt"]["seconds"] * 1000 +
latestMessage["createdAt"]["nanoseconds"] / 1000000
) >
new Date(
x["createdAt"]["seconds"] * 1000 +
x["createdAt"]["nanoseconds"] / 1000000
)
) {
latestMessage = x;
}
} else {
latestMessage = x;
}
});
return () => unsubscribe();
}, []);
I got the data from my database and i saved the oldest data in to latestMessage (for pagination) but the problem is that:
I declared my latestMessage out of my function like that:
let latestMessage = null;
export default function ChatTutor({ route }) {
...
}
And I passed my props to ChatTutor component (chatRoomId, username...) and according to that id, the room and its data are rendered. But the latestMessage always set some value and when i go to parent component and clicked another chatRoom, ChatTutor has a value of latestMessage's other value(oldest value). How can i set latestMessage null when i go to the parent ?