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

The functionality of my Javascript code is restricted to a single element within a Python embedded for loop in Django2

My Python for loop is iterating through these HTML template cards, each accompanied by JavaScript. However, I'm encountering an issue where the JavaScript only seems to work on the first element (specifically, it's meant to retrieve the seeked po ...

Semantic UI form validation is initiated by clicking any button

Within my Semantic UI form (<div class="ui form">), it seems that every button is triggering the form validation, even if it's not a submit button. I have two different types of buttons below: <button class="ui blue right labeled icon prima ...

What is the best location to include my JavaScript code in WordPress?

Alright, so I've got this world map on one of my WordPress pages and here's an example of the code: <area onmousedown="modifyImage('world_map_01', './images/map/asia.jpg')" onmouseout="modifyImage('world_map_01', ...

Is there a correct way to properly duplicate a JSON array in Redux?

As a newcomer to Redux, I found the concepts somewhat confusing at first. For instance, imagine that there is an array in the redux state. const state = [ {show: false, id : '1'}, {show: false, id : '2'}, {show: false, id : &apo ...

Iterating through an array of objects within a Vuejs template

Consider the JSON data below: { "games": [ { "id": 1, "init_date": "2020-02-11T07:47:33.627+0000", "players_in_game": [ { "id": 1, "player": { "id": 1, "player": "Jack Bauer", ...

Is your Bootstrap input displaying the has-error class with a glyphicon, but the alignment is not vertically centered?

What is the reason for the misalignment of glyphicon-warning-sign form-control-feedback vertically in the code below after applying font-size: 20px; to the label? <div class="container"> <div class="content align-left contact"> ...

Navigate to the Vuex Store to gain entry into the module

I have a module called ProfileData with the following structure: export const ProfileData = { state: { ajaxData: null; }, getters: {/*getters here*/}, mutations: {/*mutations here*/}, actions: {/*actions here*/} } This module ...

Using the Count() function in PHP to update information upon page refresh

I have created a basic cart that displays a div containing purchased items when hovered over. The issue I am facing is that every time I click on the add to cart button, it doesn't immediately update the number of items in the cart. I have to manually ...

What is the best way to combine ASP.NET Core version 2.1 with Vue CLI version 3?

My current challenge involves attempting to merge the new Vue CLI 3 with ASP.Net Core web in a new project. I am able to successfully create a blank web project using dotnet new, as well as generate a Hello World template using vue create. However, combi ...

Is there a JavaScript/jQuery timer for re-invoking a method?

Currently, I am developing a basic animation with jQuery that utilizes the hover method. The issue arises when a user hovers over the same image twice, causing the method to be re-invoked. Any recommendations on how to implement a "timer" to prevent the ...

Tips for ensuring that the toJSON method in Sails.js waits for the find operation to complete before returning the object

When I try to run a find inside the toJSON function in the model, the object is returned before the find completes. How can I ensure that the return happens only after the find operation has completed? toJSON: function() { var obj = this.toObject(); Com ...

When the state changes in React, the useSelector hook does not provide real-time updates

Currently, I am in the process of implementing a search feature using React and Redux Thunk. The main requirement for this search functionality is to fetch data from an API by calling a thunk action and updating the state accordingly for display on the UI. ...

A simple guide on accessing a local PDF file and returning it as the response for an ExpressJS application

In my ExpressJS application, I have a method for generating a PDF file and sending it to the client. However, there are cases where I need to retrieve an existing local PDF file and return it as the response. I'm unsure how to handle this scenario. ...

Show me a list of either only development or production dependencies in npm

When attempting to list only the production dependencies from package.json according to the npm docs, I tried: npm list -depth 0 -prod or npm list -depth 0 -only prod However, npm continues to list both dependencies and devDependencies. Can anyone sugg ...

Tips for navigating through a webpage by scrolling

My goal is to automatically scroll down to the bottom of the page and then perform a specific action. With the help of uiautomator, I was able to retrieve the following information: index=2, resource-id=com.manoramaonline.arogyam:id/pager,class=android.sup ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

Can a Node.js dependent library be integrated into Cordova?

After setting up an android project using Cordova, I came across a javascript library that relies on node.js to function. Since Cordova operates with node.js, can the library be invoked within the Cordova environment? ...

Updating variable values in AngularJS while navigating through routes

How can I dynamically set the flag icon inside the page header based on the selected language using AngularJS? The language selection is done in a separate .htm file and all managed by AngularJS routing. My application has a single controller called "appCo ...

An expected expression was encountered near the if condition

I am encountering an expression expected error in Visual Studio near if(isNullOr ........ if (value) { if (isNullOrUndefined(x.value) && isNullOrUndefined(x.value2)) { x.minMark + '-' + a + '*' + x.b + ' ' + ...

Best approaches for communicating form-data between parent and child components in VueJS

I am currently working on a VueJS project that involves parent and child components structured like this. Parent.vue <template> <ChildA v-bind="this.postData.someDataA" /> ... <ChildZ v-bind="this.postData.someDataZ"/> & ...