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

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a variab ...

When utilizing KineticJS on a canvas that has been rotated with css3, the functionality of the events appears to be malfunctioning

Currently, I'm working on a rotating pie-chart widget using Kineticjs. However, I have run into an issue where the events don't seem to function correctly when drawing on a rotated canvas element (with the parent node being rotated 60deg using CS ...

What causes a React Ref callback to be invoked multiple times during the initial loading of a page?

To find more information, please visit this URL within the React DOCS. You can also access a version of this code here. I acknowledge that it is recommended to use the useCallback hook in a Functional React Component to create a ref callback according to ...

Manage the Cancel button functionality in Safari/Chrome when dealing with the Open in App Store pop up

Is there a way to manage the Cancel button on the Open in App prompt when redirected from Safari/Chrome to the AppStore? The situation is as follows: A user is prompted to download the app via a browser link. Upon clicking the link, it determines whether ...

Utilizing the MEAN stack to establish a connection with a simulated data collection

Currently, I am diving into the world of M.E.A.N stack development. As part of my learning process, I have successfully set up a test page where Angular.js beautifully displays and re-orders data based on search criteria. To challenge myself further, I dec ...

How can we access a value within a deeply nested JSON object in Node.js when the key values in between are not

In the nested configuration object provided below, I am seeking to retrieve the value associated with key1, which in this case is "value1". It's important to note that while key1 remains static, the values for randomGeneratedNumber and randomGenerated ...

Revise the validation process for the drop-down menu and input field

Looking for help with text field validation based on a dropdown selection. There are two scenarios to consider: 1. User changes dropdown value and then enters text in the field. 2. User enters text in field and then changes dropdown. I've written cod ...

Exploring bidirectional component binding within Vue.js

As a newcomer to Vue.js, I was attempting to incorporate the currency filter example from the official guideline (example of currency filter). However, I encountered an issue when changing the property name of the component from 'value' to &apos ...

Trying to fetch an image from a server using VueJS?

How can I fetch an image from the server in Vue.js and display it on a Blade template in Laravel? The issue seems to be with displaying the image using the code below. <tr v-for="post in posts"> <td>{{post.title}}</td> <td&g ...

Anticipate the completion of Subject callback execution

Take a look at the code snippet below: const mA = async () => { try { const subscription = myEmitter.subscribe(url => getD(url)); const la=()=>{...}; return la; } catch (error) { throw error; } }; ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

Tips for Naming Your GitHub NPM Package for VueJS Package

I decided to customize a git repository of vuejs for my specific project needs. After successfully installing it using the command below: npm install bondythegreat/vue-input-tag --save The installation generates the following line in the package.json fil ...

"Trouble With JSON and ASP.NET WebMethod: Server-Side Method Not Executing

I am attempting to send parameters to my code behind using the WebMethod. Although I am successfully reaching the end of ajax, the method in my aspx.cs code behind is not being called and I am encountering an error. Operation failed! Details: '[ob ...

Creating a "Container" component in Vue.js step by step

As a newcomer to Vue, I am facing a challenge in implementing a wrapper component similar to React's 'Wrapper' component. Specifically, I want to create a reusable datagrid component using a 3rd-party some-table component and a pagination co ...

Encountering syntax errors in GraphQL

Currently, I am in the process of working on the GraphQL Node tutorial and have reached step 7. Visit this link to view Step 7 While implementing the code in my datamodel.prisma file, I encountered several syntax errors: directive @id on FIELD_DEFINITIO ...

Creating dynamic routes in express.js with fixed components

I'm exploring how to create a route in express that captures URLs like this: /events/0.json Here's what I've attempted so far (but it's not working as expected): router.put('/events.json/:id.json', isLogged, events.update) ...

Error Found: Syntax Error - 'if' statement not recognized

if (fname == null || fname == "") { Receiving an error message "uncaught syntax error:unexpected token if in line 13". The error indicates "SyntaxError: missing variable name" when using Javascript lint function validateRegistration() { var emailReg ...

When incorporating "<" or ">" into a parameter value in Angular Translate and then showcasing it in a textarea with ng-model

In my Angular Translate string, I am using a parameter that can be in the form of <test>. However, when this translate is displayed in a textarea, it shows up as &lt;test&gt; instead of <test>. Is there a way to ensure it appears correc ...

The child element fails to update when the properties are modified in the storage

Currently, I am utilizing Vue-js in tandem with require-js. My goal is to access data from the vuex store within my cart component so that I can render a separate component for each item stored. However, when I initiate a mutation from my body component to ...

Execute a function with parameters when a button is clicked dynamically using PHP

I am trying to execute a parameterised function in PHP using AJAX. Below is the code snippet of my dynamic button where I need to pass $sub_id to the delet(sub_id) function for executing some SQL: echo "<td><input type='submit' name=&a ...