Managing Asynchronous Operations in Vuex

Attempting to utilize Vue's Async Actions for an API call is causing a delay in data retrieval. When the action is called, the method proceeds without waiting for the data to return, resulting in undefined values for this.lapNumber on the initial call.

The action is triggered with 'this.getRound(findRound);' in the following method:

     getRaceInfo(date) {
      let showModal = false;
      let findRaceName = '';
      let findCircuitName = '';
      let findRound = '';
      let findLapNum = '';
      // iterate through each race to match date of current
      this.allRaces.forEach(el => {
        if (el.date != date) {
          return;
        } else {
          // assign variables based on matching date
          findRaceName = el.raceName;
          findCircuitName = el.Circuit.circuitName;
          findRound = el.round;
          this.fetchRoundResults(findRound);
          console.log('after fetch');
          findLapNum = this.lapNumber;
          showModal = true;
        }
      });
      // set property values according to variables
      this.raceName = findRaceName;
      this.circuitName = findCircuitName;
      this.roundNum = findRound;
      this.lapNum = findLapNum;
      return showModal ? (this.isModalVisible = true) : '';
    },

The action being invoked is:

  async fetchRoundResults({ commit }, roundNum) {
    try {
      const response = await axios.get(`http://ergast.com/api/f1/current/${roundNum}/results.json`);
      const roundInfo = response.data.MRData.RaceTable.Races[0];
      await commit('set_round_results', roundInfo);
      console.log('set result');
      return response;
    } catch (e) {
      console.log(e);
    }
  },
};

The sequence of events based on console logs:

after fetch

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property '0' of undefined"

found in

---> <RaceCalendar> at src/components/Calendar.vue
       <App> at src/components/Dashboard.vue
         <App> at src/App.vue
           <Root>
warn @ vue.runtime.esm.js?2b0e:619
logError @ vue.runtime.esm.js?2b0e:1884
globalHandleError @ vue.runtime.esm.js?2b0e:1879
handleError @ vue.runtime.esm.js?2b0e:1839
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1862
invoker @ vue.runtime.esm.js?2b0e:2179
original._wrapper @ vue.runtime.esm.js?2b0e:6911
vue.runtime.esm.js?2b0e:1888 TypeError: Cannot read property '0' of undefined
    at lapNumber (raceCalendar.js?8f5d:13)
    at wrappedGetter (vuex.esm.js?2f62:762)
    at Vue.eval (vuex.esm.js?2f62:95)
    at Watcher.get (vue.runtime.esm.js?2b0e:4473)
    at Watcher.evaluate (vue.runtime.esm.js?2b0e:4578)
    at Vue.computedGetter [as lapNumber] (vue.runtime.esm.js?2b0e:4830)
    at Object.get [as lapNumber] (vuex.esm.js?2f62:564)
    at VueComponent.mappedGetter (vuex.esm.js?2f62:900)
    at Watcher.get (vue.runtime.esm.js?2b0e:4473)
    at Watcher.evaluate (vue.runtime.esm.js?2b0e:4578)
set result

On subsequent runs, while the undefined error is resolved, the data is still not 'set' until after the method execution.

after fetch
set result

Your assistance in resolving this issue would be greatly appreciated!

Thank you :)

Answer №1

Revise your getRaceInfo function like this

async getRaceInfo(date) {
  let isDisplayed = false;
  let raceTitle = '';
  let circuitTitle = '';
  let roundNumber = '';
  let lapNumber = '';

  for await (let item of this.allRaces) {
    if (item.date != date) {
      return;
    } else {
      raceTitle = item.raceName;
      circuitTitle = item.Circuit.circuitName;
      roundNumber = item.round;
      await this.$store.dispatch('fetchRoundResults',roundNumber);
      console.log('data fetched');
      lapNumber = this.lapNumber;
      isDisplayed = true;
    }
  }

  this.raceName = findRaceName;
  this.circuitName = findCircuitName;
  this.roundNum = findRound;
  this.lapNum = findLapNum;
  
  return isDisplayed ? (this.isModalVisible = true) : '';
},

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

Retrieving PHP variable within a JavaScript file

I have a PHP script running on my server that tracks the number of files in a specific directory. I want to retrieve this file count ($fileCount) in my JavaScript code. numberOfImages.php: <?php $dir = "/my/directory/"; $fi = new FilesystemIterator($d ...

Guide on utilizing getelementsbytagname for retrieving LI values

As I attempt to locate a specific product on amazon.com, my goal is to extract the ASIN for each item. This particular code snippet runs through various search options and retrieves the price of each product from Amazon one by one. However, in addition to ...

What is the best way to set a newly selected HTML option as the first choice?

I'm facing a simple problem in JavaScript that I can't seem to crack. Admittedly, I am new to working with JavaScript. My issue lies with sorting a dropdown list in alphabetical order while also keeping the selected value at the top. Whenever a ...

React - Login page briefly appears while loading

Hello, I have built a React application that consists of a Login page, Loading page, and the main app itself. However, there is a small issue where after a user logs in, instead of smoothly transitioning to the Loading page until the data is loaded, the L ...

Deactivate a setInterval function within a Vue.js component

I am facing an issue in my VUE SPA where I have a component running a recursive countdown using setInterval functions. The problem is that the countdown continues running in the background even when I switch to another view, but I want to destroy the setIn ...

Once it hits the fourth tab, it must not cycle back to the first one

Hi there, I'm new to JavaScript I noticed that when I click the left and right arrows, the tabs circle back to the beginning However, I would like the circle to stop. When it reaches the fourth tab, it should not go back to the first. This should also ...

Using Express-session in the Internet Explorer browser

When configuring the express-session plugin, I follow this setup: var express = require('express'), session = require('express-session'), uuid = require('node-uuid'); var expiration_day = new Date('9/15/2015&apo ...

Setting up an event listener for a newly added list through the use of node appendChild

I am currently working on dynamically adding a select list to my HTML document. While I have successfully added the node to the DOM, I am struggling with creating an event listener in a separate JavaScript file that recognizes the newly created select list ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...

How to effectively delete the class from a navigation list item

Looking for some inspiration? Check out the basic visuals for this question here. But let me break it down for you. This snippet shows the HTML & CSS behind a tabbed-carousel, with a condensed version for clarity: <style> #myCarousel-100 . ...

Utilizing the forEach method for decision-making

Here is an array called 'array' with values [10, 15, 20] var array = [10, 15, 20]; There is also a variable named N with a value of 20: var N = 20; I need to iterate through the array and check if N is greater than all numbers in the array in ...

Highcharts - resolving cross-browser e.Offset discrepancies in mouse event detection on charts

I need to determine if the mouseup event is inside the chart and display the coordinates of the point. The code works in Chrome but not in Firefox due to the lack of the event.offset property. jQuery(chart.container).mouseup(function (event) { eoff ...

How to run 'npm' scripts externally in package.json on Windows?

In the world of development, running arbitrary commands using npm run is a common practice. This involves adding a scripts hash to your package.json: "scripts": { "build-js": "browserify browser/main.js | uglifyjs -mc > static/bundle.js" } To exec ...

Is there a way in Javascript or JQuery to determine if a function is currently executing, or is there a way to tap into a return event?

Let me paint a picture of a common scenario: there's a form with numerous inputs (around 60-70). Each input must undergo validation, and if it is invalid, the form returns false. To prevent multiple AJAX requests with visual feedback, I need to safegu ...

Is there a way to combine two addEventListeners into one for a single click event?

preview of a to-do list app I am faced with a situation where I have two addEventListeners, one to change the text color and another to change the circle color. In Condition 1: When I click on the circle, both the text and circle colors are changed. In ...

Is there a way to assign innerHTML values to table cells using PHP?

I'm currently building a website that relies on a database to store information. I have created an array to hold the values retrieved from the database, and now I need to populate a table with these values. Each cell in the table has a numerical ID ra ...

Is "Invalid Date" indicating an incorrect date?

Have you ever wondered why JavaScript returns 'Invalid Date' when setting an (invalid) date? It can be quite confusing and make it difficult to handle errors. So, what is the optimal way to deal with this issue? One approach is to check the date ...

Cease running code post while loop (do not use break)

I need help with my code that checks if a user is already in a Database. Once the while Loop runs, it verifies the presence of the MC Player in their Database through the Mojang API. However, if the user is already in my Database, I want to skip the Mojang ...

Is there a way to prevent Express from automatically adding a slash to a route?

Despite my extensive search for a solution, none of them have proven effective. Perhaps you could provide some assistance. I'm currently working on a Node.JS and Express-based plugin webserver. The main code for the webserver is as follows: This sec ...

Troubleshooting ng-bind-html issue with displaying images loaded using CSS within HTML content

I followed the instructions provided in a related post on the same topic. I used 'ngSanitize' and formatted the HTML content using 'sce.trustAsHtml()', and it rendered correctly when the HTML contained both text and images. However, I e ...