I have a chat application. In this chat application, messages sent in the past are visible, but as the number of messages increases, the page length increases too much. Can I paginate every 10 posts as 1 page in this app?
JavaScript code that adds past chats:
socket.on('old_messages', (msg) => {
msg.forEach(element => {
let messageContent = " <p class='card'><b>" + element.username + ": </b>" + element.content + "</p>";
MESSAGE_LIST.innerHTML = messageContent + MESSAGE_LIST.innerHTML;
});
});
3
Answers
For UI: Ideally, your chat application should be a defined sized div on the page in which the messages are shown. You can enable scroll in that div and keep the view at the most recent message.
For messages: Show N number of messages at a time and old messages should not be rendered when the user scrolls towards them.
Option 1 Fetch messages from the backend when user scrolls towards the old messages. This assumes that you have a paginated API that can return N number of messages based on page size and page number.
Option 2 If you don’t have backend paginated API to pull messages then you can store messages in different array in frontend and rendered messages using different array. As the user scrolls, move the messages from first array to second to render them. NOTE: This method will make the webpage slower as the number of messages will increase.
Well, you can use Array.slice method to get the pagination done.
But this is not the best catch, actually.
The best practice is to make the backend send the data according to pagination options.
you can try the following: