In this episode, we update our messaging component so that it can fetch and load previous messages as the user scrolls up—essentially building out the "infinite scroll" for a chat.
First, we set up the ability to pass a room slug as a prop into our message viewer, so we know which conversation to load more messages for. Then, over in our store (where we're tracking messages), we add a new action called fetchPreviousState
to handle loading earlier messages for the room.
We make sure that each time this function is called, it requests the correct page from the backend, incrementing the page number accordingly so we don't just keep getting the same old batch of messages. Laravel's built-in pagination on the backend takes care of stitching everything together, so when we scroll up, the previous set of messages just gets pushed onto the start of our message array.
By the end of the video, we see that scrolling to the top loads more and more messages as expected, and we even discuss how to control the initial number of messages loaded. All in all, it's a nice step towards a slick, user-friendly chat experience!