What is the best way to pre-fetch data using axios in Vue?

My app requires offline functionality for drivers operating in remote areas with limited internet access. To address this, I aim to pre-download all necessary data using Axios requests when an internet connection is available. This way, the app can retrieve data from cache instead of relying on the server.

I have attempted a solution, but it does not seem to follow best practices.

  tryOffileWorkSheet: async function () {
      Network.addListener("networkStatusChange", (status) => {
        if (status.connected) {
          setInterval(function () {
            let worksheet = JSON.parse(localStorage.getItem("worksheet"));
            if (worksheet == null) {
              worksheet = [];
            }
            
            for (let i = 0; i <= worksheet.length; i++) {
                      if(worksheet.length > 0){
                     setTimeout(function () {
                       if(worksheet[i]?.work_order_id){
                      ApiService.get(
                        `/api/gangBoss/work-sheet/${worksheet[i].work_order_id}/${worksheet[i].column_name}/${worksheet[i].value}`
                      ).then((response) => {
                         if(response.data.status){
                      worksheet.splice(i,1)
                      localStorage.setItem("worksheet", JSON.stringify(worksheet));
                         }
                         console.log('After', worksheet)
                      });
                       }
              },i* 3000);
                      }
            }
          }, 3000);
        }
      });
    },

In addition, user interaction on a page should trigger data downloads when internet connectivity is detected. This may involve downloading large amounts of data.

Can you suggest the best practice or recommend a Vue plugin to streamline this process?

Answer №1

It seems like the question is a bit unclear and may not be the best fit for this platform, but I'll do my best to provide an answer.

Upon reviewing the code, one key issue stands out which is the usage of setInterval. The problem lies in how it is implemented as there is nothing stopping the interval from running continuously. Let me illustrate this with a scenario:

  • networkStatusChange event triggered: status.connected === true
  • interval #1 created by setInterval
  • After 3 seconds, interval #1 fires
  • This cycle continues for the next 2 hours
  • networkStatusChange event triggered: status.connected === false
  • However, interval#1 keeps firing
  • networkStatusChange event triggered: status.connected === true
  • Another setInterval creates interval #2
  • Within 3 seconds, both interval #1 and #2 fire
  • This process persists with both intervals firing every 3 seconds

The main issue here is that the interval continues to fire regardless of the current connection status, causing unnecessary operations.

A more efficient approach would be to trigger the function every 3 seconds using a single timer and exiting if the connection is unavailable. This method also leverages window.navigator.onLine, which has broader browser support.

Addtionally, calling the ApiService with a delay of 3 seconds between each call and invoking the parent function cyclically might result in excessive API requests depending on the size of worksheet.

tryOffileWorkSheet: function () {
    // Ensure `intervalId` exists in the data
    if (this.intervalId) clearInterval(this.intervalId);
    
    this.intervalId = setInterval(() => {
      if (window.navigator.onLine) {
        this.getWorkSheet();
      }
    }, 3000);
  },
  getWorkSheet: function () {
    let worksheet = JSON.parse(localStorage.getItem("worksheet"));
    if (worksheet == null) {
      worksheet = [];
    }
    for (let i = 0; i <= worksheet.length; i++) {
      if (worksheet.length > 0) {
        setTimeout(() => {
          if (worksheet[i]?.work_order_id) {
            ApiService.get(
              `/api/gangBoss/work-sheet/${worksheet[i].work_order_id}/${worksheet[i].column_name}/${worksheet[i].value}`
            ).then((response) => {
              if (response.data.status) {
                worksheet.splice(i, 1);
                localStorage.setItem("worksheet", JSON.stringify(worksheet));
              }
              console.log("Updated worksheet:", worksheet);
            });
          }
        }, i * 300);
      }
    }
  },

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

Angular not detecting changes in string variables

Issue with variable string not updating var angulargap = angular.module("angulargap", []); angulargap.factory('cartService', function($rootScope,$http){ var fac ={ message:"factory", getCart:function(call){ $h ...

Jquery loop using closures

I've been working on creating a plugin that involves passing handler functions for specific events. Consider the scenario below: I have two buttons, and when I click button 1, its label is supposed to change to 'Button A', while clicking but ...

Prevent users from inserting images from their desktop into the HTML by disabling

While working on a HTML5 drag and drop image uploading feature, everything was going smoothly. I had a small div in the HTML with a JavaScript event handler set up like this: $('#uploader').on('dragover', function(e){ ... }).on(&apos ...

Calculator built with HTML, CSS, and JavaScript

Hi there, I'm experiencing some issues with my calculator. The buttons seem to be working fine and lining up correctly, but for some reason, nothing is showing up on the monitor or getting calculated when I press the buttons. Here's the code that ...

In a Next.js application directory, how can you retrieve the router.asPath value within a function that utilizes the Next.js navigation feature?

import { useRoute } from "next/navigation" const route = useRoute() const updateData = () => { route.replace(route.asPath); } I attempted using next/router but it was unsuccessful ...

Unable to execute a GET request using the Fetch API on Django REST Framework results in receiving an HTTP 304 error code

When attempting a GET request with the Fetch API (Node Fetch) module against a Django REST API, I am encountering a 304 error. I am unsure of how to resolve this issue as it seems to be related to requesting the same data repeatedly. Is there no way around ...

Mastering the Art of Page Scrolling with d3

I would like to implement a scrolling effect for my d3 that allows the entire page to scroll while panning, similar to the effect on challonge (http://challonge.com/tournaments/bracket_generator?ref=OQS06q7I5u). However, I only want the scrolling to occur ...

Discovering the minimum and maximum within an array containing objects

I am working with an array of objects that contain latitude and longitude points: var pts = [ { "X": 52.67528921580262, "Y": 8.373513221740723 }, { "X": 52.6759657545252, "Y": 8.374114036560059 }, { "X": 52.682574466310314, "Y": 8.372569084 ...

Polyfill for window.showOpenFilePicker function

Could anyone recommend a polyfill for the window.showOpenFilePicker method? For reference, you can check out the documentation on MDN. ...

Is there a way to make Express JS always serve files from the current directory no matter the route?

Currently, I am developing an Express app utilizing the Handlebars template engine. The HTML files it serves have images that direct to specific locations in my root directory. Everything works seamlessly for basic routes like "http://localhost:5000/image" ...

Encountering the 'currently unable to handle this request' issue while trying to render an inertia component in Laravel 8 with vue.js

Encountering an error message that says "currently unable to handle this request" while trying to render an inertia component from app/Exceptions/Handler.php in Laravel 8. Software Versions: @inertiajs/vue2 version: 1.0.3 @inertiajs/inertia-laravel versi ...

Implement a unique feature for specific days using jQuery UI Datepicker with a customized class

Looking to highlight a range of days horizontally in jQuery UI Datepicker with the multiselect plugin. To achieve this, I am utilizing the :before and :after pseudoelements of the a tags. .ui-state-highlight a:before, .ui-state-highlight a:after { con ...

Issue with Vue v-for not updating data model variable

I am attempting to render a page with dynamic properties using the following code: <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="root"> <div v-for="current in 2&quo ...

React not functioning properly when packaged with Webpack

I tried implementing React in the simplest way possible, but I am facing some issues. After bundling React and opening the index.html page, it shows up completely blank with no console errors to indicate any mistakes. Below is my webpack.config.js: const ...

Communication between the content script and background page in a chrome extension is not functioning correctly as intended

Displayed below is the code I posted: manifest.json { "manifest_version": 2, "name": "Demo", "description": "all_frames test", "version": "1.0", "background": { "scripts": ["background.js"] }, "content_scripts": [{ "matches": ...

The jQuery mouseout functionality seems to be malfunctioning and not responding as expected

I am currently developing a slider that displays details when the mouse hovers over the logo, and hides the details when the mouse moves away from the parent div. jQuery('.st_inner img').mouseover(function() { jQuery(this).parent().siblings( ...

Struggling with making react-hook-form correctly validate an email address

I've been struggling for a long time to make this validation work correctly, but it seems impossible. I even added some text at the bottom to display an error message related to the email, but it always shows no error, regardless of the situation. Ed ...

Modify div content based on user selection

I have a question about updating the content of a div based on certain conditions in my code. Here is what I'm trying to achieve: <div class="form-control" ns-show="runningImport" disabled="disabled"> {{input[row.header_safe]}}{{select[row. ...

The loading on the Express endpoint does not cease, despite configuring the response status (Encountering problems with Multer and Express)

Currently, I am in the process of developing a filter that evaluates a file's signature obtained through a file's buffer provided by Multer. While Multer supplies the MIME type, additional validation methods are required to confirm if the file ma ...

Retrieve posts based on categories using the WordPress REST API and Vue.js

I'm currently attempting to retrieve post data using the Wordpress Restful API. My progress so far includes: Upon loading the app, fetching the initial page of posts. If the user clicks the 'load more posts' button, another page of posts i ...