I have been developing a news application with Vue 3 and the News API. I am currently implementing a feature for loading more articles on the page.
Initially, there are 24 articles displayed, and if there are more articles available than the current number being shown, a "Load more articles" button appears at the bottom of the page.
In the file src\components\ArticleList.vue
, the following code is present:
<template>
<div v-if="articles && articles.length" class="row">
<div
v-for="article in articles"
:key="article._id"
class="col-xs-12 col-sm-6 col-lg-4 col-xl-3"
>
<ArticleCard :article="article" />
</div>
<div v-show="isMore" class="mb-3 text-center">
<LoadMoreButton @load-more="loadMore" text="Load more articles" />
</div>
</div>
<p v-if="totalResults == 0" class="text-center">No articles to display</p>
</template>
<script>
import ArticleCard from "./ArticleCard.vue";
import LoadMoreButton from "./LoadMoreButton.vue";
export default {
name: "NewsList",
components: { ArticleCard, LoadMoreButton },
props: {
whatToShow: {
type: String,
required: true,
},
searchString: {
type: String,
required: true,
default: "",
},
},
data: () => ({
language: "en",
page_size: 24,
current_page: 1,
totalResults: 1,
articles: [],
}),
mounted() {
this.getArticles();
},
watch: {
whatToShow() {
this.getArticles();
},
searchString() {
this.getArticles();
},
},
computed: {
isMore() {
let totalPages = Math.ceil(this.totalResults / this.page_size);
return totalPages > this.current_page;
},
},
methods: {
getArticles() {
const endpoint = `${process.env.VUE_APP_API_URL}/${this.whatToShow}?q=${this.searchString}&language=${this.language}&pageSize=${this.page_size}&page=${this.current_page}&apiKey=${process.env.VUE_APP_API_KEY}`;
this.$axios
.get(endpoint)
.then((response) => {
this.totalResults = response.data.totalResults;
this.articles = [...this.articles, ...response.data.articles];
})
.catch((err) => console.log(err));
},
loadMore() {
if (this.isMore) {
this.current_page++;
this.getArticles();
}
},
},
};
</script>
The file
src\components\LoadMoreButton.vue
contains the following code:
<template>
<button class="btn btn-md btn-success" @click="$emit('load-more')">
{{ text }}
</button>
</template>
<script>
import { defineComponent } from "vue";
export default defineComponent({
name: "LoadMoreButton",
props: {
text: {
type: String,
required: false,
default: "Load more",
},
},
});
</script>
The computed property isMore
determines whether to show the "Load more articles" button based on the availability of additional articles to load.
However, after clicking the LoadMoreButton
for the last time, no additional articles are loaded before the button disappears. The error code received in the response is "maximumResultsReached".
A complete code sandbox can be found HERE.
I'm seeking guidance on what might be causing this issue and the most effective way to resolve it.