How can we ensure that the load more button disappears at the appropriate moment in this Vue 3 application?

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.

Answer №1

My recommendation is to monitor the server for changes in the maximumResultsReached property. Once it indicates true, you can then set isMore to false. This method appears to be more straightforward and easier to implement.

Answer №2

Make sure your loadMore function is expecting a boolean value from the computed property it relies on. Currently, it seems like you are only checking for values greater than a certain number, which might cause issues when the value is equal to that number. To ensure that the last page of data is loaded correctly, make sure that both the last page and the total number of pages are represented by the same integer value and return true accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

unable to display loading image prior to upload

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="en"> <head> <title>Unique Prints</title> <meta charset="utf-8"> <meta name="viewport" conte ...

"Enhance Your Website with Custom jQuery Preloaders

Currently, I am facing a challenge while developing a website. Specifically, I am struggling with resolving the issue of a blank page being displayed. The website that I am working on involves functionality where swiping right triggers data insertion into ...

Functionality of Ajax: Data fields containing numerous values

I'm confused about the data fields in the ajax function. Typically, the syntax for an ajax function looks something like this: $.ajax({ url: "/aaa/bbb/ccc", method: "SomeMethod", data: someData, success: function (res ...

Creating a universal method in Vue.js 2 and passing parameters

I have a scenario where I need to update the title and description in a component's mounted() lifecycle hook. However, I am looking to create a global function that can be reused for this purpose. Is there a way to achieve this efficiently? window.d ...

Vue-moment displaying incorrect time despite timezone setting

Feeling a bit puzzled about my Laravel 8 application. I store time in UTC with timestamp_no_timezone in my PostgreSQL database. When I check the time in the database, it displays today's date with 13:45 as the time. However, when I use vue-moment and ...

What is the best approach to incorporating Ant-design-vue via cdn in my project?

I've been working on a Vue macro application for specific functionality in NetSuite. Since I can't utilize npm or other package installers, I've resorted to using CDN. The Vue app and Ant Design are both functioning properly, but the issue l ...

The process of deleting lines from an image using Javascript

If I have an image of a data-table and I want to eliminate all the grid lines (defined as continuous vertical or horizontal pixels), is there a way to achieve this using Javascript's image data manipulation? I envision looping through a 2D array conta ...

The code line "npx create-react-app myapp" is not functioning as expected

When running the command 'npx create-react-app my-app', I encountered the following error message: Error: '"node"' is not recognized as an internal or external command, operable program or batch file. Before suggesting to cre ...

Switching styles in AngularJS without using ng-class

My goal is to allow users to switch the class from incomplete to complete when they click a button and the function(response) returns 1. I have attempted to use ng-class, but it is not effective because the HTML elements are generated with a PHP loop. This ...

Searching in sequelize for a specific date using a clause

Operating System: Linux (Lubuntu) Programming Language: Javascript (Node js) Framework: express js Database: mysql "data" represents a Date field from the "activitat" table Upon running this query using Sequelize.js models.TblActivitat.findAll( ...

Tips for excluding certain parameters in the jslint unparam block

While developing my angular app, I encountered an issue with jslint flagging an unused parameter. Typically in angular, the "$scope" is required as the first parameter in your controller definition. In my case, I prefer using the "this" keyword instead of ...

Can someone please show me the process of iterating through an array in vuejs?

I am trying to create a Vue.js method that loops through an array of objects and returns all the names in that array. However, I am not sure how to achieve this. The method implementation would look something like this: fruits =[ {name: "apple", calori ...

Completing a form and saving data to a document

I have a form that successfully writes to a text file using PHP. However, after submitting the form, the page reloads and shows a blank page. Currently, there is a message that appears using jQuery after the form is submitted. My goal is to prevent the pa ...

Troubleshooting Vue.js: Why is .bind(this) not behaving as anticipated?

Demo: https://codesandbox.io/s/23959y5wnp I have a function being passed down and I'm trying to rebind the this by using .bind(this) on the function. However, the data that is returned still refers to the original component. What could I be missing h ...

What could be the reason for my React Component not properly associating with the image?

The title appears to be correctly displayed, but there seems to be an issue with the images. I've thoroughly reviewed the code multiple times, but unfortunately, I'm unable to identify the problem. Please provide guidance on what changes need to ...

Is there a way for me to choose all the classNames that conclude with a specific word within the MUI sx property?

I am currently working with MUI and I have a need to modify certain properties that are prefixed with random IDs. How can I target, for instance, the first one using: '& endsWith(MuiAccordionDetails-root)' I wish to achieve this because the ...

Redirecting script upon successful connection detection

I have created a script that checks for internet connectivity using an image, and redirects if internet is available. However, the issue is that it caches the images, leading to attempts to load them even when offline. Is there a different approach I can ...

What is the reason behind using <script> tag for scripts, instead of using <style> tag for external CSS files?

A family member who is new to Web Development posed an interesting question to me. Why do we use <script src="min.js"></script> and <link rel="stylesheet" href="min.css">? Why not simply use <style href="min.css"></style>? Wh ...

Verify if the JSON response contains any data

When the JSON response is empty and viewed in the browser console, it appears like this: {"data":{},"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://url/form/BN217473" ...

JavaScript encountering a NaN value

I'm encountering an issue where I am receiving a NaN when attempting to summarize columns of a report. Additionally, my query is only retrieving 1 row of data, but the grid is displaying 2 rows. Does anyone have any suggestions on how to resolve this ...