Issue with Vue.js: "Load more data" button functionality malfunctioning

I've been working on my Vue.js code and I'm trying to implement a "Show More" button for the data fetched from an API. Initially, only 10 items should be displayed, and when the button is clicked, it should load another 10 items and so on. I checked out a solution on Stack Overflow at this link:

Load more button in vuejs

However, I encountered an error while looping over an array with the message

"can't read property of question title"
. Is there a way to resolve this issue?

<div class="search-askbutton">
            <b-row>
              <div class="search-wrapper">
                <input
                  type="text"
                  v-model="search"
                  placeholder="Search something..."
                  class="fas fa-search"
                />
                </div>

<div class="container vue">
<div v-for="commentIndex in commentsToShow"> 
    <div v-if="commentIndex <= commentsToShow">
        <ul
           class="container-question"
           v-for="(question, index) in filteredList"
           :key="index"
        >
            <div>{{question[commentIndex - 1].questionTitle}} says:</div>
            <hr />
        </ul>
    </div>
</div>
   <button @click="commentsToShow += 10">show more</button>
</div>

<script>
export default {
    data() {
        return { commentsToShow: 10,
        search: '',
        questions: [],}
    },
     computed: {

    filteredList() {
      return this.questions.filter((question) => {
        return (
          question.questionTitle
            .toLowerCase()
            .includes(this.search.toLowerCase()) ||
          question.owner.username
            .toLowerCase()
            .includes(this.search.toLowerCase()) ||
          question.questionTitle
            .toUpperCase()
            .includes(this.search.toUpperCase()) ||
          question.owner.username
            .toUpperCase()
            .includes(this.search.toUpperCase())
        );
      });
    },
  },
    mounted: function() {
    questionService.getAllQuestions().then((response) => {
      this.questions = response.data.response;}
}
</script>

Answer №1

The issue lies with the subtraction operation

<div>{{question[commentIndex - 1].questionTitle}} states:</div>

When commentIndex equals 0, the calculation becomes 0-1 = -1, causing it to search for an index that doesn't exist.

To resolve this, you can update the following line of code

<div v-if="commentIndex <= commentsToShow">

This change will ensure that the code only runs if the index is greater than 0

<div v-if="commentIndex > 0"> 

Answer №2

1)

v-for iterates through the elements inside an array, not the array itself.

<div>{{question.questionTitle}} says:</div>

2)

Additionally, it is possible to eliminate the v-for loop.

Note: The reference question also follows this approach.

<div v-for="commentIndex in commentsToShow"> 
 <div v-if="commentIndex <= commentsToShow">
   <ul class="container-question">
    <div>{{filteredList[commentIndex - 1].questionTitle}} says:</div>
   <hr />
   </ul>
 </div>
</div>

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

Warning users when submitting a form if required fields are left empty

As a Python developer, I have been delving into Vue.js development. I have a function similar to a() in Python that takes iterables. If all items in the iterable are true, then all([...]) returns true. methods: { all: function(iterable) { for ...

Images in Prismic fail to load on Vue website, causing runtime and compiler errors

I recently incorporated the prismic.io headless cms into my vuetify project successfully to display content from text fields created in my prismic repository. However, I'm facing difficulties when it comes to loading images. Upon checking the console ...

Is it possible to create a Facebook reveal tab using either Javascript or .NET?

As a developer who jumped into Facebook development just before the recent changes, I am feeling lost when it comes to building apps now. I see many questions similar to mine about creating fan-gating features using Javascript only. Is there an up-to-date ...

The validity of AngularJS form is constant and always returns true with formName.$valid

I am facing an issue with my Angular application form where even though the input fields are blank, formName.$valid is always true. Below is the HTML code for my form: <form name="contactForm" novalidate ng-submit="processForm(formData)" autocomplete=" ...

Trouble with loading document on 'load' event listener

Primary Concern Currently, my script operates smoothly when it listens for a click event on the element with the id share. I am looking to switch this functionality to activate on the $(document).on(load) event while removing the share button. However, up ...

The element is implicitly assigned an 'any' type due to the fact that an expression of type 'any' cannot be used to index types in nodejs and solidity

I am in need of setting networks in my contract using NodeJS and TypeScript. Below is the code I have written: let networkId: any = await global.web3.eth.net.getId(); let tetherData = await Tether.networks[networkId]; Unfortunately, I encountered ...

Discover the best correlation among multiple arrays

I am currently developing a chat script that allows users to specify their interests. Upon connecting to the server, the client sends a JSON payload over WebSocket containing information such as ID, hash, auto message, and interests. {"id": int, "hash": m ...

What is the process for interacting with a Node.js Web API using an Angular JS API?

Seeking assistance with converting HTML into JADE format, encountering issues with {{record.name}} not functioning correctly. This is preventing the fetching and printing of values. Below are the complete file details: Directory view can be seen here. JS ...

Event on FullCalendar is directing to an incorrect URL

After integrating FullCalendar to my website following a tutorial, everything seems to be working fine except for the URLs added to events on the calendar. Instead of directing me to the specified URL when I click on an event, it redirects me to a differen ...

What is the best way to retrieve the ID of a conditionally displayed item within a modal component?

I am facing an issue with my notes component where I need to delete a specific note based on its ID after accepting a modal confirmation. It works fine without the modal, but I want to ensure that the note is only deleted when the modal is accepted. This ...

Modify CSS class if user is using Internet Explorer version 10 or above

I am attempting to modify the CSS of 2 ASP controls using jQuery specifically for users accessing the site with Internet Explorer 10 or 11. This adjustment is necessary because IE10 onwards, conditional comments are no longer supported. My approach to achi ...

JavaScript: Adding up whole numbers--- Reference Error: Undefined

I'm having trouble with my code because it's saying that "t1" is not defined, even though it's the name of my text box. I tried making the variable global by declaring it outside the function, but it didn't solve the issue. Interestingl ...

I'm curious why my phone number is being treated as an object when it's passed in as a prop

I am facing an issue with my FooterScroll component while using it on the TvIndex main page. This is the FooterScroll Component const FooterScroll = (Id: number) => { const { event } = useEvent(Id); console.log('Id', Id); return ( ...

My experience with jquery addClass and removeClass functions has not been as smooth as I had hoped

I have a series of tables each separated by div tags. Whenever a user clicks on a letter, I want to display only the relevant div tag contents. This can be achieved using the following jQuery code: $(".expand_button").on("click", function() { $(th ...

Automatic page switch upon dropdown selection

I'm not very proficient in JavaScript and I want to modify a form so that it automatically updates when a dropdown option is selected, without needing to click a separate "Go" button. How can I adjust the code below? It contains three different dropd ...

What is the best way to integrate the each_slice method in Rails views with React components

In my Parent component Monsters, I am rendering the Monster component. for each monster in @state.monsters React.createElement Monster, key: monster.id, monster: monster, team: @state.team... Within the monster: div className: 'col-md-4' ...

Vue: Issue with Firebase Authentication REST API triggers 400 Bad Request Error

Here is the error message I am encountering: POST scheme https host identitytoolkit.googleapis.com filename /v1/accounts:signUp key AIzaSyAk1ueCLjDDWCNrt_23o5A4RCfeaYIlN6k Address 74.125.24.95:443 Status 400 Bad Request VersionHTTP/3 Transferred850 B ...

What is the best way to retrieve all the listed TV and film ratings in descending order? Using Django

Our Goal I aim to organize movies based on their star ratings and filter out those with ratings lower than a specified threshold. 2. Retrieve the IDs of Movies and TV shows mentioned in the view, fetch the data and score through URLs one by one. 3. Presen ...

Tips for incorporating Javascript Object Literals into Python code

Using the Beautifulsoup module, I successfully extracted an HTML page and then proceeded to extract a Javascript script tag from that page. Within this script tag lies an object literal that I hope to manipulate. Here is what I am aiming for: <script&g ...

Implementing bi-directional data binding between sibling components in Vue.js

Is it possible to create a dual binding scenario with the typeahead plugin https://github.com/pespantelis/vue-typeahead, where the search terms of two typeaheads are linked? This means that regardless of which search box the user types into, both should ...