In this episode, we focus on hooking up our front-end Vue app to fetch and display posts from the backend, and we add basic pagination so users can load more posts as they scroll or click a button.
We start by taking some pre-built markup (made with Tailwind) and integrating it into our app. This markup includes a textarea for posting, a section to list out the posts, and a "Load More" button. Then, in our script section, we use the script setup syntax to make things cleaner and use the composition API's ref
to store our posts array.
Next, we import Axios and write a fetchPosts
function to grab posts from our API when the component mounts. We store the results in a posts
ref, handle the nested "data" property from Axios, and display the posts on the page. We map through these posts using v-for
, outputting each post's body and ID.
For pagination, we check our API response for a next_page_url
and store this in its own ref. When the load more button is clicked, we use this URL to fetch the next batch of posts. Originally, this replaced the existing posts, but we tweak it so that the new posts are added to the end of our existing array by combining the old and new arrays.
By the end, clicking "Load More" correctly appends more posts to the list. In the next episode, we plan to tackle adding new posts and making sure they show up at the top of the list, while considering how that affects our pagination logic.