What is the process to update the v-overlay value using component getters?

When working with a Vue.js application component that retrieves information from Vuex storage, I need to display a v-overlay (preloader) until the data from storage becomes available. What is the correct approach to achieve this?

<template>
  
    <v-navigation-drawer
      v-model="open"
      absolute
      right>
  
      <v-overlay
        :absolute="absolute"
        :opacity="opacity"
        :value="overlay">
      
        <v-progress-circular
          indeterminate
          size="64">
        </v-progress-circular>
  
      </v-overlay>
  
      <v-checkbox
        v-if="!overlay"
        hide-details
        v-model="selectedGenders"
        v-for="gender in genders"
        :label="gender"
        :value="gender"
        :key="gender">
      </v-checkbox>
  
      <v-checkbox
        v-if="!overlay"
        hide-details
        v-model="selectedIncomeRanges"
        v-for="incomeRange in incomeRanges"
        :label="incomeRange"
        :value="incomeRange"
        :key="incomeRange">
      </v-checkbox>
  
    </v-navigation-drawer>
  
  </template>
  
  <script>
  import {
    mapGetters,
    mapActions
  } from 'vuex'
  
  export default {
    name: 'RightNavigationDrawer',
    props: {
      open: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        absolute: true,
        opacity: 0.8,
        overlay: true,
        selectedGenders: [],
        selectedIncomeRanges: []
      }
    },
    mounted () {
      this.getGenders()
      this.getIncomeRanges()
    },
    computed: mapGetters('customStore', [
      'genders',
      'incomeRanges'
    ]),
    methods: mapActions('customStore', [
      'getGenders',
      'getIncomeRanges'
    ])
  }
  </script>

Answer №1

It's best practice to maintain the status of loading in vuex so that it can be accessed across all components just like any other vuex state. Start by setting up a boolean state called loading in your store. Then, create a loading action which can be triggered in the component as follows:

fetchData({ commit, dispatch }) {
  commit('SET_LOADING', true);
  const loader1 = dispatch('fetchUsers')
  const loader2 = dispatch('fetchPosts')
  Promise.all([loader1, loader2]).then(() => {
    commit('SET_LOADING', false);
  })
}

The Promise.all method takes an array of promises from your loading actions and waits for all of them to resolve before continuing. Make sure that your fetchUsers and fetchPosts actions also return promises. Now, in your component, only map the loading and fetchData actions:

...mapState('myStore', ['loading']),
...mapActions('myStore', ['fetchData'])

Update the lifecycle hook mounted to call the fetchData action:

mounted() {
  this.fetchData()
}

With this setup, you can easily access the loading status throughout your components without managing it separately. This approach ensures that the loading state is centralized in vuex along with other states, making it readily available across your components.

For a demonstration, you can check out this demo which simulates asynchronous calls using timeouts. (Note that the example combines vuex and vue in a single file, so the structure may appear a bit different but is easy to follow.)

Answer №2

Make sure to monitor the overlay variable in Vuex storage. Let's assume its value is this.overlay = true

watch: {
    overlay (val) {
      val && setTimeout(() => {
        this.overlay = false
      }, 3000)
    },
  },

Check out this CodePen link

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

Displaying a loading spinner while waiting for the Vue.js app to render

Currently, I am developing a Vue.js application and I'm facing a challenge in adding a loading spinner before the app component is rendered. Instagram has a similar feature where they display their logo before showing the page contents. I have tried v ...

The stylesheet_pack_tag seems to be malfunctioning as it is not producing any output, despite the fact that the CSS file exists

After a Rails update, we encountered an issue with the stylesheet_pack_tag in our VueJS client application. Even though Webpacker successfully generates the CSS file in the /public/packs folder along with other files such as JS, the stylesheet_pack_tag s ...

Warning: Using synchronous XMLHttpRequest on the main thread is no longer recommended as it can negatively impact the user's experience

I encountered an issue with my project while attempting an Ajax request [Warning] Using synchronous XMLHttpRequest on the main thread is now considered deprecated due to its negative impact on user experience. function retrieveReviews() { var reviewsD ...

Jquery script that utilizes the Steam WebAPI to return data

I'm encountering an issue with a script I found on github. I added value.appid myself, thinking it was logical, but I believe that data.response.games contains values for all my games. How can I either print or view what is defined? I would like to ...

I am struggling to comprehend the code for a PHP form that triggers a JS OnUpdate event, which then uses AJAX to retrieve data from MySQLi

I want to give a special thanks to Alon Alexander for providing the JS and AJAX code, even though I don't fully comprehend it. I am more comfortable using PHP/JS without jQuery, but I am struggling to make it function as intended. My current issue in ...

The middleware for express body-parser stores information in the "name" property

I'm just starting out with the nodeJS Express framework and I'm currently working on consuming a POST request that I sent using the code snippet below: router.post('/', function(req, res) { var data = Object.getOwnPropertyNames(req ...

Angular reactive forms can be customized to include a patched version of the matTime

I have an angular mattimepicker in my project. When trying to use it in a reactive form, I am encountering issues with patching the value to the edit form <h1>Reactive Form</h1> <form [formGroup]="form"> <mat-form-fie ...

What is the best way to display components in VueJS?

I am looking to dynamically render a component based on my variables with the following code: <div>{{ auth ? <AuthCorrect /> : <AuthIncorrect /> }}</div> However, my application is currently rendering it like this: {{ auth ? auth ...

Activate continuous speech identification

Is it possible to activate the capability of recognizing continuous speech through the REST API (using javascript SDK) with the Bing Speech API? The Javascript SDK example available at https://github.com/Microsoft/Cognitive-Speech-STT-JavaScript only seem ...

What are some solutions for resolving the issue of a neutralino white screen?

After setting up a new neutralino js application, I encountered an issue where upon running it with the 'neu run' command, all I see is a blank white screen. I tried using the CheckNetIsolation.exe ... command to troubleshoot the problem, but unf ...

Declining the request to incorporate an external website into my web platform

While checking the console errors in Google Chrome, I encountered the following error message: The page 'https://website.com' was blocked from framing because a higher-level ancestor violates the Content Security Policy directive: "frame-an ...

Guide to generating a PDF file and utilizing a Node.js program for the download process

Seeking assistance in creating a button using my Node.js application to generate a downloadable PDF file filled with information from a PostgreSQL database. Any help is greatly appreciated! ...

send array to the sort function

How can I sort a data array that is returned from a function, rather than using a predefined const like in the example below: const DEFAULT_COMPETITORS = [ 'Seamless/Grubhub', 'test']; DEFAULT_COMPETITORS.sort(function (a, b) { re ...

Changing color based on AngularJS condition using CSS

My HTML code looks like this: <div> <i class="glyphicon glyphicon-envelope" style="margin-top: -50px; cursor:pointer; color: #1F45FC" ng-click="createComment(set_id)"> </i> Route <center> ...

Check the length of a ngRepeat array after the initial filtering before applying limitTo for further refinement

Currently, I am implementing pagination in my Angular application by using a custom startAtIndex filter along with the limitTo filter. My goal is to show the total number of results in the dataset, regardless of the current page. However, due to the use of ...

Having issues with setting up nodejs on kali linux

Whenever I try to execute the configure script ./configure for nodejs installation, it fails to run successfully. Traceback (most recent call last): File "./configure", line 19, in <module> from distutils.spawn import find_executable ModuleN ...

Issue with Google Charts where the label does not show outside of the bar if the bar is too small

I am encountering an issue with my Google Bar Chart where the bar label is not displaying outside of the bar when it is too large to fit inside. This behavior should be the default, but my charts are not working as expected. The problem can be seen in rows ...

Manipulate classes based on scrolling (Wordpress)

Trying to manipulate a widget by adding and removing classes based on user scroll behavior has proven to be quite challenging. Specifically, I aim to add one class when the user scrolls down by 50px and remove it when they scroll back up. Website: Check o ...

Sending Dual Parameters to PHP File Using AJAX

Currently, I am facing an issue where I can successfully pass one value to a Bootstrap modal via AJAX, but my code stops working when I try to pass a second value. JavaScript function claimOrder(str, stre){ if (str=="") { document.getElementById("txtH"). ...

Having difficulty creating a shadow beneath a canvas displaying Vega charts

I'm looking to create a floating effect for my chart by adding shadows to the canvas element that holds it. Despite trying various methods, I can't seem to get the shadow effect to work. Here is the code snippet I have for adding shadows: <sc ...