0

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 ?

3
  • did you consider using unmount lifecycle useEffect hook? There you can just clean it up. Commented Feb 22, 2021 at 12:05
  • But I want to clean it up just when i go to parent component. Does it work in that situation?@TukaramBhosale Commented Feb 22, 2021 at 12:08
  • when you navigate away from child, it will get unmounted, I hope it should work in that case. Commented Feb 22, 2021 at 12:17

1 Answer 1

1

You can use useRef to store local mutable data (it would not participate in re-renders):

export default function ChatTutor({ route }) {
  const latestMessage = useRef(null);  // null is initial value
  // ...
  latestMessage.current = 'some new message' // set data
  console.log(latestMessage.current) // read data
  return <>ChatTutor Component</>
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.