Displaying outdated data while loading fresh content in VueJS app

Imagine having a Vue3 app with a store where the state is structured like this:

const store = {
    state () => ({
        items: []
    }),
    // ...
}

Within the App.vue file, there is only a single <router-view /> as the template content.

Additionally, there exists an ItemList.vue view with the following structure:

<template>
    <div v-if="!loading">
    <Item
        v-for="item in items"
        :key="item.id"
        :item="item"
        ></Item>
    </div>
    <Skeleton v-else />
</template>

<script>
import Item from "...";
import Skeleton from "..."

import { mapState } from "vuex";

export default defineComponent({
  name: "CourseList",
  mixins: [loadingMixin],
  components: {
    Item, Skeleton
  },
  async created() {
   this.loading = true
   this.$store.dispatch("getItems", {
       categoryId: this.$route.params.categoryId
   })
   this.loading = false

  ...

});

</script>

The functionality of the app allows users to visit URLs such as categories/<id>/items and access items specific to that category. A flat array stores the viewed items within the store's state. Whenever the ItemList component is initialized, an action triggers an API call to retrieve new items for display. In the meantime, a loading skeleton is presented to the user for visual feedback.

An issue arises when navigating back to the same category view as previous visits may still trigger a re-fetching of items, resulting in unnecessary delays if the data has not been updated. The challenge lies in displaying existing data without waiting for a refresh while maintaining the ability to fetch new content when necessary.

Is it possible to achieve this behavior in Vue? Attempts using the <keep-alive> component and assigning a :key based on the route's category ID parameter have proven ineffective so far.

Answer №1

To dynamically update the 'loading' state based on the user's visited categories, you can implement a conditional check within the Vue component. If the category has changed, set the 'loading' state to true. Otherwise, utilize a Vuex store and maintain the previous 'categoryId' value in a Set object.

async created() {
   if( the category has changed){ 
      this.loading = true
   }

   this.$store.dispatch("getItems", {
      categoryId: this.$route.params.categoryId
   })
   
   this.loading = false
}

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

Troubleshooting problem with hiding options in Jquery Chosen

Utilizing the chosen multiple selection feature, I have encountered an issue where selected options remain visible after being hidden and updated. Here is the code snippet: $("#ddlcodes").find("option[value ='" + codeValue + "']").hide(); $("#d ...

A status code of 200 indicates a successful login, which then leads to a 401 status code upon making a

Just recently, I successfully deployed a rails backend and a vue frontend to Heroku. Everything was working fine until today when I encountered a problem while trying to log in to the web app. Immediately after logging in, I started receiving 401 responses ...

What is the best method for eliminating duplicate values within d3?

Is there a way to display only unique values in the legend for a scatterplot created in d3? Another question I have is how can I remove commas from the axis labels? To visualize this issue, here is the current look of the plot: https://i.sstatic.net/X1h0 ...

Tooltip remains visible even after formatting in highcharts

I have successfully hidden the datalabels with 0 values by formatting them. However, after formatting the tooltips for 0 valued data in a pie chart, there is an issue where hovering over the 0 valued portion shows a white box as shown in the picture. I hav ...

NextJs only displays loading animation once

Currently, I am developing an app using Next.js and I am facing a challenge with implementing a loading animation. The animation I am attempting to incorporate consists of three bouncing balls which display correctly. When I launch the Next.js app with n ...

The countdown timer resets upon the conditions being rendered

I have been using the 'react-timer-hook' package to create stopwatches for each order added to an array. The problem I encountered was that every stopwatch, across all components, would reset to zero and I couldn't figure out why. After a lo ...

Bringing in States and Functions to a React Component

Is there a way to improve the organization of states and functions within a functional React Component? Here's my current code structure: import React from 'react' //more imports... const Dashboard = () => { const [] = useState() / ...

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 ...

Logs from console.log() statements in Firebase functions are missing

I've encountered an issue with the function below where the console.log() statements do not appear in the Firebase logs. When I remove everything after the db.collection call, the initial console.log() statements are visible. However, once I reintrodu ...

Exploring the plane intersection within a 3D object using Three.js

I attempted to create an animation using Three.js to display the intersection plane on a 3D object with the following code snippet: import React, { useRef, useEffect, useState } from 'react'; import * as THREE from 'three'; export cons ...

Changing profile picture using React UI framework

I'm just starting with react so please bear with me if I make any mistakes. I am trying to figure out how to update a user's profile picture. I need to create a clickable image (with the variable name "avatar" in the code) that will show a previe ...

Detecting incorrect serialized data entries based on data types

In the scenario where the type MyRequest specifies the requirement of the ID attribute, the function process is still capable of defining a variable of type MyRequest even in the absence of the ID attribute: export type MyRequest = { ID: string, ...

Incorporate JSON data into a JavaScript search in CouchDB

I am currently working with a CouchDB database that contains approximately one million rows. My goal is to query for specific rows in the database using the keys provided in an external JSON file. The approach I am currently using to achieve this involves ...

Having trouble with the function not running properly in HTML?

I'm having trouble implementing a copy button on my HTML page. Despite no errors showing in the chrome console, the text just won't copy. Below is a snippet of my HTML code: <!doctype html> <div class="ipDiv tk-saffran"> <div c ...

Can TypeScript be used to dynamically render elements with props?

After extensive research on SO and the wider web, I'm struggling to find a solution. I have devised two components, Link and Button. In short, these act as wrappers for <a> and <button> elements with additional features like chevrons on t ...

While continuing to input text, make sure to highlight a specific element from the search results list

Currently, I am using a customized search feature in my React.js application. I am looking for a way to focus on an element within the search results so that I can navigate using arrow keys. At the same time, I need to keep the input field focused to conti ...

Adjust width based on value dynamically

I currently have a div that is sized at 250px, housing 3 child divs within it. My goal is for each of these 3 divs to dynamically scale based on their respective values, eventually reaching 100% width. This is the code snippet I am working with: <di ...

How can I prevent a hyperlinked element from being clicked again after it has been clicked using JavaScript or jQuery in PHP

I am struggling with disabling the href after it has been clicked. Can someone please assist me with this? It is crucial for me to complete this PHP program. Style.css .disabled { pointer-events: none; } ...

The integration between Vue.js Vue Router and Firebase hosting seems to be experiencing some issues

I'm encountering an issue with Vue Router. While navigating between views/pages using the Navbar works fine, I face an error when trying to access a specific page directly through the domain/url. Firebase (where my website is hosted) throws an error c ...

Adjust the canvas size to fit its parent element ion-grid

I am currently working on an Ionic 3 component that displays a grid of images connected by a canvas overlay. I have utilized Ionic's ion-grid, but I am facing an issue with resizing the canvas. The problem is that I cannot determine the correct dimens ...