14. Load More Button – Fetch Previous Messages

Right now, you have noticed that you are only able to view the last 30 messages. This is because, in the twelfth chapter, we are fetching only the last 30 messages from Mongo DB. But how can you see the old messages? We can do that by creating a “load more button”.

To do that, first, we need to create a button that when clicked will an AJAX to get the previous messages. So write the following code before your <li> messages loop in ChatComponent:

<li style="text-align: center;">
	<i v-bind:class="btnLoadMoreClass + ' btnLoadMore'" v-on:click="loadMore" v-if="hasMoreMessages"></i>
</li>

Then we need to create the following variables in our data() object.

btnLoadMoreClass: "fa fa-repeat",
hasMoreMessages: true,

After that, you need to add the following CSS styles in your chat.css:

.btnLoadMore {
    transform: rotate(270deg);
    font-size: 30px;
    color: darkgray;
    cursor: pointer;
}

This will show a load more button before messages.

load more button
load more button

Now, we need to create a function that will increment the page variable and send the AJAX again to fetch old messages. So, create the following method in your methods object.

loadMore: function () {
	this.btnLoadMoreClass = "fa fa-spinner fa-spin"
	this.page++
	this.getData()
},

And when the data is fetched, we need to stop the spinning icon. The following code goes in the getData() method when the response is received from the server.

this.btnLoadMoreClass = "fa fa-repeat"

The last thing you need to do is to remove the load more button if there are no more old messages. So when the response status is “success”, we do the following:

this.hasMoreMessages = (response.data.messages.length == 0) ? false : true

This will check if the old message’s length is zero, then it will hide the button, otherwise, it will display the button. Now you can test the app. Click on the load more button, it will start spinning and as soon as the data is received from the server, the spinner stops, and the old messages will be prepended to the chatbox. And if there are no more old messages, then the load more button will be hidden.

To learn more about this functionality, check out our detailed tutorial on this.