Implement a loading bar on the entire page in Vue.js while a request is being made

There is an "edit" button on my page which allows me to edit certain elements and either save or close without saving.

I would like to implement a loading bar that displays when the user clicks the "save" button, indicating that the data is being processed before showing the results.

Current functionality:

After clicking the "edit" button, editable data appears with options to "save" or "close" (which dismisses changes). Clicking "save" reloads the page with updated data and displays an "updated" message, or shows an error message if the update fails.

Desired functionality:

Upon clicking the "save" button after making edits, I want the page to show a loading bar for a few seconds (e.g. 5 seconds). If the request completes within that time, the loading bar disappears; otherwise, it continues until completion. The page then displays the updated data and the "updated" notification.

Below are snippets related to this feature:

Button setup:

Insert code snippet here

Edit function:

Insert code snippet here

For the progress bar, I am utilizing Vuetify's circular progress component.

   <v-progress-circular
    v-show="loading"
    indeterminate
    color="primary">
   </v-progress-circular>

Struggling to determine where in the code to place this element for it to display correctly throughout the entire page. Placing it before or inside the buttons has not yielded the desired result.

Answer №1

If you're looking for a solution, one approach could be to implement an overlay that is positioned at the bottom of your root element.

Here's a basic example to give you an idea:

         <v-col cols="3">
          <v-btn
            v-if="editGroup"
            light
            class="mx-2"
            @click="editGroup = false"
          >
            <v-icon left>mdi-close</v-icon>
            Close
          </v-btn>
          <v-btn
            v-if="editGroup" 
            light 
            class="mx-2" 
            @click="clickSave"
            >
            <v-icon left>mdi-content-save</v-icon>
            Save
          </v-btn>
          <v-btn
            v-if="
              canShowButton(['administrator', 'configurator']) &&
              !editGroup
            "
            light
            class="mx-2"
            @click="editGroup = true"
          >
            <v-icon left>mdi-pencil</v-icon>
            Edit
          </v-btn>
          <--The overlay will only display when loading state is true-->
          <v-overlay v-model="loading">
            <v-progress-circular
            indeterminate
            color="primary">
            </v-progress-circular> 
          </v-overlay>
        </v-col>

The overlay will be visible across the entire screen as long as the loading state remains true.

Check out the Vuetify documentation on overlays for more information.

Edit:

In addition, make sure to initialize the loading state in the data section of your page upon initial load.

<script>
  export default {
    data: () => ({
      loading: false,
    }),
    },
  }
</script>

Answer №2

State management with tools like pinia is essential for efficient data handling. By setting up a pinia store in the following manner:

import { defineStore } from "pinia"

export enum PageState {
  LOADING,
  LOADED,
  ERROR
}

export const usePageStore = defineStore({
  state: () => ({
    pageState: PageState.LOADED
  }),
  getters: {},
  actions: {
    saveData(endpointPrefix, groupId, newData) {
      try {
        // Perform URL building and data processing here
      } catch (e) {
        throw new Error(e)
      }
    },
  },
})

Instead of handling all data operations within your Vue script, you can simply do this:

pageStore = usePageStore()

async clickSave() {
  try {
    pageStore.pageState = PageState.LOADING
    const response = await pageStore.getData(this.endpointPrefix, this.groupId, dat)
    this.$nuxt.$emit('show-notification', {
          text: 'updated',
          color: 'green',
        })
    this.loadData(this.groupid)
    pageStore.pageState = PageState.LOADED
  } catch (e) {
    pageStore.pageState = PageState.ERROR
     this.$nuxt.$emit('show-notification', {
        text:
          'could not be updated !' +
          error.response.data,
        color: 'red',
      })
  }  
}

Your main page view can then access the same store, monitor that variable, and adjust accordingly to display the necessary information.

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

What steps should I take to optimize the performance of this code by implementing rate-limiting for its execution speed?

As I pondered the task at hand, I realized that using a sleep function might be beneficial. However, Javascript lacks a built-in sleep function. How can I tweak this process to avoid hitting a Parse rate-limit? My goal is to execute one (1) Parse.Cloud.ru ...

Is Node.js going to continue to provide support for its previous versions of node modules?

I currently have a website that relies on the following dependencies. While everything is working smoothly at the moment, I can't help but wonder about the future support of these packages by node.js. I've looked into the legacy documentation of ...

What steps do you take to establish a relay connection for pagination in an ORM framework?

After thorough research of Relay's documentation, I have yet to find a clear explanation on how to establish a Relay connection with an ORM. The examples provided mainly utilize the connectionFromArray method, which works well for data stored in memor ...

Script on Tampermonkey executed prior to page loading

I am facing a challenge with hiding a specific section from an HTML page: <h1 data-ng-show="!menuPinned &amp;&amp; !isSaaS" class="logo floatLeft" aria-hidden="false"><span>XXX&nbsp;</span><span style="font-weight: bold;"& ...

React error message: "Cannot update state on a component that is not mounted" unless using the useEffect hook

(I am a beginner using Next.js + Styled Components and need help :)) I'm currently working on creating a "Netflix" style page, with unique catalog components. Each content item in the grid is a complex component named ContentItem.js that is repeated ...

Using NodeJs to pass values to a callback within a condition statement and retrieve the returned value

Within my routing file, I have implemented a condition where an external function is used to compare two values: obj.id === getId. Based on whether this condition evaluates to true or false, the view is rendered, or the user access is blocked. The functio ...

Cleaning up HTML5 video content

I have been on the search for a solution that would allow me to "scrub" through HTML5 video. So far, I have not come across one and was considering developing my own. However, before diving into that process, I wanted to seek advice from the community here ...

Simple server using node.js and express to host an HTML file and associated resources

I am currently experimenting with frontend development and need a basic web server to quickly start projects and serve files. Specifically, I have one index.html file along with some css/js/img files. I decided to work with Node.js and Express for this pur ...

After refreshing the page, the Vue instance that was imported is not defined within the created or mounted hooks

I am attempting to integrate a feature in Vue that will automatically log in the user after the page is reloaded. I have imported the Vue instance into a module responsible for sending HTTP requests. This module is then imported into the main component of ...

Revamp your code by utilizing ES6 class to replace multiple if statements in Javascript

Currently, my code is filled with numerous if statements and I am considering a switch to classes in ES6. However, Javascript isn't my strong suit... so PLEASE HELP ME..! Previous code: //example code function first(){ console.log('first sce ...

What could be causing an error in a scroll handler when using React's setState function?

Upon reaching the bottom of the page and scrolling back up, an error is thrown by React stating "TypeError: _this.setState is not a function" The scroll handler in question monitors the position of the client on the page. If the client is within the home ...

Turn off Babel's strict mode when transpiling JavaScript files

Currently, I am facing an issue while trying to transpile a set of JavaScript files using Babel. Since Babel operates in strict mode by default, it triggers a syntax error whenever there is a conflict like the use of the delete keyword. The solution I am s ...

What is the best way to fill a "multiselect" element with information from a JSON object?

I'm struggling to populate the multiselect field with data from a JSON object. No matter which multiselect I use, the data shows in inspect mode but not on the frontend. It was supposed to look like this. https://i.sstatic.net/FVz2H.png but it comes ...

Refreshing an order in Laravel and Vue using axios

Having an issue with refreshing data after executing the axios method. Specifically, I am encountering problems when changing statuses. My goal is to display only the status name without any buttons once the status is changed. However, the order does not r ...

What could be the reason for the absence of 'server' and 'client'?

Trying to retrieve data from db.json but facing some challenges. Below is the content of my db.json file: { "posts": [ { "id": "react-hooks", "title": "React Hooks", "content": "The greatest thing since sliced bread!", "author": "ali" }, ...

The callback function for the `input` component in React Native must be a function and should not be undefined. Always remember to start component names with the proper syntax

There was a gap in my project as I have an application currently under development for testing purposes. Error: The view config getter callback for the component input must be a function (received undefined). Make sure to capitalize component names. I am ...

Troubleshooting Angular 2 ng-if issues

Is there a way to dynamically apply CSS styles to an element that has an ng-if condition, even if the condition fails? It currently works fine when the condition is true, but I'm looking for a solution that allows me to modify the element regardless o ...

Ways to ensure the text on my website scrolls into view as the user navig

Is there a way to have my text show up as I scroll? I came across this , but I'm interested in how it actually functions. I saw a similar inquiry before, but it doesn't make sense to me. Can someone please explain or provide some examples on how ...

Occasionally, data may fail to be fetched when using a Jquery GET

Here's what I've narrowed it down to: $.getJSON('/drinks/getColors', function(items) { colors = items; }); $.each(colors, function(index2, value2) { if (value.name == value2.name) { curColor = value2.color; } }); ...

Fetching data during Nuxt 3 server initialization: A step-by-step guide

In the process of migrating a web app from Nuxt 2 to Nuxt 3, there is also a companion API responsible for data fetching from databases. The webserver must fetch a JSON object containing startup settings and constant variables necessary for runtime paramet ...