Displaying a progress bar while fetching data in Vue: A step-by-step guide

I am working on developing a progress bar using vue js and bootstrap for my desktop application. Within the template, I have the code that will generate the necessary markup:

    <div class="container-fluid p-0 vh-100" v-if="isLoading">
        <div class="row m-0">
            <div class="col-4 mx-auto">
                <div class="progress rounded-0" role="progressbar">
                    <div class="progress-bar text-uppercase" id="progressBar" style="width: 0%;"></div>
                </div>
            </div>
        </div>
    </div>

In a specific method, I have the following code, in which I need to incorporate some logic to load data and update a Supabase database. My goal is to hide the progress bar once all the data has been loaded:

        updateDatabase() {
            const preloader = document.getElementById('progressBar')
            setTimeout( () => { 
                preloader.style.width = '15%'
                preloader.style.width = '30%'
                preloader.style.width = '45%'
                preloader.style.width = '60%'
                preloader.style.width = '75%'
                preloader.style.width = '90%'
                preloader.style.width = '100%'
            }, 1500)
            //other db logics
        }

Additionally, I have a data property called isLoading that is initially set to true when the progress bar and database loading/update process are ongoing. However, I noticed that the progress bar disappears immediately, which was not the intended behavior. How can I properly implement a timeout function to gradually adjust the width percentage of the progress bar? Setting the isLoading variable at the end of the timeout causes it to be set to false immediately, resulting in the disappearance of the progress bar. Any guidance on this issue would be greatly appreciated. Thank you.

Answer №1

In the given example, the setTimeout function will wait for 1500ms before executing the code inside it. This will result in the width changing from 15 to 30 to 45, and so on. If you want to display progress continuously, you should use an interval that increases the width incrementally until it reaches 100% and then removes the isLoading flag. You can achieve this by utilizing setInterval as shown below:

this.interval = setInterval(() => {
  if(this.width === 100) {
    this.width = 0;
    clearInterval(this.interval);
    this.isLoading = false;
  }
  const newWidth = this.width + Math.floor(Math.random() * 15);
  this.width = this.newWidth <= 100 ? newWidth : 100;

  preloader.style.width = this.width + '%';
}, 150);

Make sure to define interval and width within your data object. This is a simplistic demonstration, but I hope it illustrates my point. Good luck!

P.S. To add a touch of randomness, a random value between 0 and 15 has been included in the example to create a more natural effect ;)

P.S. P.S. In Vue, it is recommended to select elements using $refs. Set the ref attribute on the element (e.g., ref="progress-bar") and access it in your code using this.$refs['progress-bar'];

Answer №2

setTimeout( () => { 
   preloader.style.width = '15%'
   preloader.style.width = '30%'
   preloader.style.width = '45%'
   preloader.style.width = '60%'
   preloader.style.width = '75%'
   preloader.style.width = '90%'
   preloader.style.width = '100%'
}, 1500)

When assigning multiple values to an attribute at the same time, only the last assignment will take effect. Therefore, in this case, only preloader.style.width = '100%' will be executed.

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

An alternative to Beautiful Soup for Python 3.2

Looking to create a web crawler for extracting information from various web pages, I discovered Beautiful Soup which seemed like an excellent tool. It allows me to parse entire documents, create dom objects, iterate through them, and extract attributes sim ...

How can I output HTML code using php echo without using quotation marks?

My issue involves printing out HTML code that is not stored as a simple string, requiring me to decode it before echoing. The problem arises when I echo the decoded value and unwanted quotes appear, disrupting the output. Here's an example: <div> ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

Ways to protect against form hacking on the client-side

As I contemplate the benefits and drawbacks of utilizing frameworks like VueJS, a question arises that transcends my current coding concerns. Specifically, should form validation be executed on the client side or through server-side processing by a control ...

Implementing image change on dropdown selection using jQuery click event

I'm new to Jquery and JavaScript. I have a dropdown in my Keen template that displays 2 flags. I want to be able to click on the dropdown and select the corresponding flag. Most of the examples I found online use the select and options tags, but my co ...

I am facing an issue with my Vue.js code where I am encountering errors when attempting to insert data into the database. Can

I encountered three distinct errors when trying to submit data from the form The first error states: [Vue warn]: Error in mounted hook: "TypeError: this.getAllUsers is not a function" Furthermore, when testing form validation without entering any informa ...

Believing in false promises as true is what the statement assumes

I'm working on authentication for my app and encountered the following code: const ttt = currentUser.changedPasswordAfter(decoded.iat); console.log(ttt); if (ttt) { console.log('if thinks ttt is true'); The changedPasswordAfter fu ...

Guide on how to validate react-multiselect with the use of Yup validation schema

If the multiselect field is empty, the validation message 'Product is required' is not being displayed. How can I validate this field? Here is the validation schema: validationSchema={ Yup.object().shape({ productID: Yup.string().requi ...

I have just started a new project in Vue and noticed that the app div has some extra margin around it. Can anyone

In my fresh Vue project, I have the following code: App.vue: <template> <div id="app"> <p>hello</p> </div> </template> <script> export default { name: 'App', components: { } ...

Creating Component Variants for Google Optimize A/B testing in Next.js

I've been attempting to create a component variant in Google Optimize beyond just text or color changes, but I haven't found a suitable method to do so yet. I'm looking for guidance on how to integrate/configure Optimize with my code in orde ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

Unable to display select options in Laravel blade due to Vue.js v-for issue

It is expected that the result will display the value of the id <select class="form-control" name="uploaded_segment_id" id="uploaded_segment_id" required=""> <option value="">Choose Segment</option> <option v- ...

Insert a design layout into a text entry box

Currently developing an application with AngularJS and seeking a solution for adding a "template" to an HTML input field similar to a placeholder. Specifically, I have a date-field requiring user input in the format of dd/MM/yyyy or through a datepicker se ...

I encountered an error while trying to add a document to Firestore using the 'add' method in Vue.js. Can someone provide guidance on how to

Whenever the function is triggered (on click), I aim to include a new document. Although it functions with .set(), my goal is for a new document to be created each time the form is submitted. The current error code I am encountering is: I initially suspe ...

Flask caches JSON files automatically

I am currently working on a visualization app using js and python. The functionality of my app is as follows: There is a textbox in the browser where I input an URL The URL is then sent to Python via Flask In Python, the URL is processed to create ...

Creating an array of objects sorted in alphabetical order

My task involves working with an array of objects that each have a name property: var myList = [{ name: 'Apple' }, { name: 'Nervousness', }, { name: 'Dry' }, { name: 'Assign' }, { name: 'Date' }] ...

Unable to execute multiple instances of Selenium PhantomJS concurrently

I have encountered an issue while using Selenium's node.js API to run PhantomJS instances against a series of web pages. The code that I have written to perform actions on the pages is functioning correctly, but it appears that only one instance of Se ...

What is the best way to update the src of an input using an onclick event?

When I click the input, my background changes color as expected. However, the src of the input only changes on the second click. How can I make it change the source on the first click? Also, how can I change the src back to the original with a second cli ...

The pug blend fails to produce the desired output

Recently, I've encountered an issue while working with Pug in a Vue.js application. The task at hand is to create a multi-level menu (with submenus) using the provided data structure: mounted () { this.catalog = [ { title: "Компр ...

Upgrading to Angular 2: Utilizing ElementRef in ES5

Currently, I am facing a challenge in creating an Attribute directive for Angular 2 that would allow me to set multiple default HTML attributes using a single custom attribute. My intention is to apply this directive specifically to the input element. Howe ...