Using Vue3 and Vuex4: How to efficiently render only a subset of items from an array with v-for

Hello, I'm a first-time user and beginner developer seeking some assistance. I am in the process of creating a basic web application that retrieves an HTTP JSON response from an API and displays a more visually appealing list of results. However, I've encountered an issue where only the initial few results from the response array are being rendered when using a v-for directive. Below is my main.js code snippet:

import { createApp } from 'vue';
import { createStore } from 'vuex';

import App from './App.vue'
import Axios from "axios";

const store = createStore({
    state(){
        return {
            searchResults: null,
        }
    },
    getters: {

    },
    mutations: {
        setResults(state, payload){
            state.searchResults = payload.claims;
        },
        clearResults(state){
            state.searchResults = null;
        }
    },
    actions: {
        submitSearch(context, payload) {
            context.commit('clearResults');
            Axios.request({
              baseURL: "https://factchecktools.googleapis.com/v1alpha1/claims:search",
              method: "get",
              params: {
                languageCode: "en",
                query: payload.searchTerm,
                pageSize: 100,
                key: "AIzaSyCqYStCPuaamvXv1qcuWeof0pEx8TguXeY",
              },
            })
              .then((response) => {
                context.commit('setResults', {claims: response.data.claims})
                //this.$store.dispatch('setResults', {result: response.data.claims})
                //this.searchResults = response.data.claims;
                //this.$emit("search-results", this.searchResults);
              })
              .catch((error) => {
                console.log(error);
              });
        },

    },
})

Here is my app.vue:

<template>
  <div class="container">
    <ClaimSearch @search-results="setResults" />
    <ResultCard
      v-for="(result, index) in searchResults"
      :key="index"
      :claim="result.text"
      :claimant="result.claimant"
      :date="result.claimDate"
      :reviews="result.claimReview"
    />
  </div>
</template>

<script>
import ClaimSearch from "./components/ClaimSearch.vue";
import ResultCard from "./components/ResultCard.vue";

export default {
  name: "App",
  components: {
    ClaimSearch,
    ResultCard,
  },
  computed: {
    searchResults(){
      return this.$store.state.searchResults;
    }
  },
};
</script>

Here's my ClaimSearch.vue component:

<template>
  <form @submit.prevent="submitSearch" class="searchBar">
    <input type="text" v-model="searchTerm" />
    <button type="submit">Is it true?</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      searchTerm: null,
    };
  },
  computed: {},
  methods: {
    submitSearch(){
      this.$store.dispatch('submitSearch', {searchTerm: this.searchTerm})
    }
  },
};
</script>

And finally, here's my ResultCard.vue component:

<template>
  <div class="resultCard">
    <div class="claimCard">
      <h3>The Claim:</h3>
      <p>{{ claim }} - {{ claimant }}, on {{ date.slice(0, 10) }}</p>
    </div>

    <div class="checkCard">
      <h3>Fact Check:</h3>
      <hr />

      <div v-for="review in reviewList" :key="review.url">
        <b>{{ review.publisher.name }}</b>
        rated this claim as "<b>{{ review.textualRating }}</b>". <br />
        Source: "<a :href="review.url" target="_blank"> {{ review.title }} </a>"
        <br />
        - published {{ review.reviewDate.slice(0, 10) }}. <br />
        <hr />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ["claim", "claimant", "date", "reviews"],
  data() {
    return {};
  },
  computed: {
    reviewList() {
      return this.reviews;
    },
  },
};
</script>

When I make an API call and receive, for example, an array of 100 items, only a portion of them appear - sometimes not displaying at all. Any ideas on what might be causing this issue? Thank you for your assistance!

And yes, I am aware that I'm a total newbie in this area!

Answer №1

After building and deploying the app, I was able to resolve the issue. It seems like there might be an error with Vue causing the v-for function to break when testing on a local development server.

Appreciate the assistance!

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

The child div can be scrolled horizontally, while the parent window remains fixed

I am facing a challenge with my HTML and CSS setup. I want to create a child div that scrolls horizontally, but I do not want the parent window to scroll along with it. Below is my current code: <div id="parent"> <div id="div1"> . ...

The python-pyinstrument is in need of a javascript dependency that seems to

As I attempt to profile my Python program using pyinstrument, I encounter an error when trying to view the profile in HTML format. Traceback (most recent call last): File "/home/ananda/projects/product_pred/025200812_cpall_ai_ordering_model_v2/.venv ...

Executing mathematical calculations within a JavaScript object

Can an equation be executed inside an object? For instance: var taxes = { gst: '0.10', }; var prices = { first_key: '437.95', total_key: parseFloat(prices.first_key * taxes.gst).toFixed(2), ....... }, }; Or do I n ...

Learn how to synchronize global packages across multiple computers using npm

After installing several npm global packages on my work computer, I am now looking to synchronize these packages with another device. In a typical project, we utilize a package.json file to keep track of package details, making it easy to install all the ...

Tips for Locating an Element by Its Attribute in JQuery

I currently have a variable that holds a list of selects, and my goal is to filter out only those with a 'dependsOn' attribute set to 'EventType'. My initial attempt below doesn't seem to work as intended and returns a count of 0: ...

Cleve js does not include delimiters in its date output

In my Vue.js project, I decided to implement a date input field using cleave.js. After passing the following options: options="{date: true, delimiter: '/', datePattern: ['m', 'd', 'Y']}" I encountered an issue wh ...

``What is the best approach for specifying property types when passing props to grandchildren within a Vue.js component hierarchy

I have a Vue component named foo embedded in my HTML, and I am passing a parameter to it as shown below: <foo some="Some String"></foo> Within the foo component, I define the property type and default value in the following manner: export d ...

The Angular service/value is failing to retrieve the updated variable from the $(document).ready() function

Currently, I'm facing an issue with my Angular service/value. It seems to be grabbing the original variable instead of the new one that is supposed to be inside $(document).ready(). Here's the relevant code snippet: var app = angular.module("app ...

Is it possible for the await block to be located outside of the async function that contains it?

setInterval(() => { // perform certain actions }, 1000) const bar = async () => { const response = await api_request(); do_actions(); } await bar(); When the foo function is set to run, will it interfere with the execution of the setInterval ...

Losing $scope reference when incorporating a directive within the controller scope

I have a scenario in my code where I am using two directives. One directive is within the controller scope, while the other directive is not located in the html section. <div ng-show="isStore==true"> <packgroup-directive> ...

Show the meta-field mp3 and place it in a lightbox container on the portfolio page

My Current Portfolio Gallery Setup: Currently, my portfolio gallery is displayed in a masonry grid format using the JIG plugin. This grid showcases images from my custom post_type. When clicking on a thumbnail, a lightbox pops up showing the full photo. T ...

Change a JavaScript object into an array with different options while still maintaining the keys

I am attempting to transform the following JavaScript object: image_uploads: [ 0: { upload_id: 50, }, 1: { upload_id: 51, }, 2: { upload_id: 52, }, ] Into separate entries using this structure for inclusion in the body of a POST r ...

What is the reason for the Client Height value not affecting other elements?

I'm trying to set the spacing of my sidebar from the top equal to the height of the header. However, when I use clientHeight in JavaScript to get the height and then try to apply it to other elements using marginTop or top values (with position includ ...

In Angular, the process of duplicating an array by value within a foreach function is not

I have been attempting to duplicate an array within another array and make modifications as needed. this.question?.labels.forEach((element) => { element["options"] = [...this.question?.options]; // I've tried json.stringify() as wel ...

The variable 'firebase' is nowhere to be found

I am encountering an issue with the error message 'Can't find variable: firebase' and I am struggling to identify the cause of this error. I have installed firebase using 'yarn add firebase' and double-checked that it is properly i ...

Is it possible to uncheck a checkbox from a list, even if some of them are already unchecked?

I am attempting to implement a feature where checking a checkbox selects all others in the list, and unchecking one deselects all. Currently, only selecting one checkbox allows me to check all the rest, but unchecking one doesn't trigger the reverse a ...

Retrieving text content from multiple classes with a single click event

There are numerous elements each having class names p1, p2, p3,...p14. Consequently, when attempting to extract text from the clicked class, text from all classes is retrieved! For instance, if the expected text is 80, it ends up being 808080080808080808 ...

Customize data appearance in Django Admin interface

I am working with a model that has a json field. The data stored in this field may not always be pretty-printed, and I am okay with it as long as it is valid. However, when the data is displayed in Django admin, I would like it to be pretty printed for eas ...

Transforming the output of a MySQL query into a JSON format organized like a tree

This question has been asked before, but no one seems to have answered yet. Imagine a scenario where a MySQL query returns results like this: name | id tarun | 1 tarun | 2 tarun | 3 If we were to standardize the JSON encoding, it would l ...

React frontend communicating without backend server

Is it possible to send a message between two frontend users on web applications built with React? ...