The second function in Vue.js was unable to initialize the data field within data() due to a missing call for assistance

I have very little experience working with vue js.

There are two functions that I am using: loadComponentsOfUser() and loadUserId(). The loadComponentsOfUser() function depends on the userID field being loaded by the loadUserId() function.

data() {
  return { 
    userId: ''
  }
},

created() {
  this.loadComponentsOfUser()
},

methods(): {
   loadUserId() {
       axios.get('getUserId').then(res => {
            this.userId = res.data
        }).catch(() => {
            ...
            })
        });
     },
     loadComponentsOfUser() {
         this.loadUserId()
         axios.get('users/' + this.userId).then(res => {
         }).catch(() => {
             ...
             })
         });
}

The loadUserId() function is functioning correctly in fetching the correct value from the server.

However, when loadComponentsOfUser() is called, it appears that the this.userId field has not been initialized and an empty field is passed to axios.

My main concern is why the field was not initialized after the loadUserId() call?

Answer №1

To receive responses, it is recommended to utilize the async and await functions:

new Vue({
  el: '#demo',
  data() {
    return { 
      id: 1,
      userId: '',
      user: null
    }
  },
  created() {
    this.loadComponentsOfUser()
  },
  methods: {
    async loadUserId() {
       await axios.get('https://jsonplaceholder.typicode.com/users/' + this.id)
         .then((res) => {
           this.userId = res.data.id
         })
         .catch(() => {})
    },
    async loadComponentsOfUser() {
      await this.loadUserId()
      if(this.userId) {
        axios.get('https://jsonplaceholder.typicode.com/users/' + this.userId)
          .then(res => {
            this.user = res.data
          })
          .catch(() => {})
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
  <input type="number" v-model="id" /><button @click="loadComponentsOfUser">load</button>
  {{ user }}
</div>

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 compilation of the module has encountered an error with the PostCSS loader. There is a SyntaxError at line 2, character 14 indicating an unknown

I am developing an Angular 8 application. Currently, I am incorporating AlertifyJs into my project. In the styles.css file of Angular, I have imported these libraries: @import '../node_modules/alertifyjs/build/alertify.min.js'; @import '. ...

JavaScript: Closing a Tab

Using AngularJS for my project and I have a link that opens a tab. If the user right clicks on the link and selects open link in new tab, then on the page abc.html I have code like $window.close(); which is not working as expected. I am receiving the error ...

How to effectively manipulate nested arrays in JavaScript without altering their references

Welcome everyone, I've been working on a project using next.js and I've encountered an issue with filtering posts. The filter function works perfectly when the posts are in a simple array like ObjChild. However, I have another section on my site ...

Saving a PHP form with multiple entries automatically and storing it in a mysqli database using Ajax

My form includes multiple tabs, each containing various items such as textboxes, radio buttons, and drop-down boxes. I need to save the content either after 15 seconds of idle time or when the user clicks on the submit button. All tab content will be saved ...

Using Typescript, Angular, and Rxjs to retrieve multiple HttpClients

I am looking to send get requests to multiple endpoints simultaneously, but I want to collect all the responses at once. Currently, this is how a single endpoint request is handled: public getTasks(): Observable<any> { this.logger.info('Ta ...

Steps for returning a res.send(req.body) upon sending back to a function

I'm currently working on sending the req.body from a POST request route back to the executing function for further processing. The structure of req.body is as follows: { username: 'aa', password: 'ss' } After making the post requ ...

Mastering the use of getText() in Protractor with Page Object Model in Javascript

Having trouble retrieving specific values from my page object. The getText() method is returning the entire object instead of just the text, likely due to it being a Promise. I can provide my code if necessary, but I'm aiming to achieve something sim ...

Expanding the input focus to include the icon, allowing it to be clicked

Having trouble with my date picker component (v-date-picker) where I can't seem to get the icon, a Font Awesome Icon separate from the date-picker, to open the calendar on focus when clicked. I've attempted some solutions mentioned in this resour ...

Error message: "An issue occurred with the Bootstrap Modal in

I've designed an AngularJS app like so: <!DOCTYPE html> <html ng-app="StudentProgram"> <head> <title>Manage Student Programs</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2. ...

Is it possible to limit the values of parameters with react-router?

Currently, I am in the process of developing a website using react and react-router. I have two different types of routes set up, as shown below: <Route name="products" path="/:type/*" handler={ ProductList } /> <Route name="generic-template" p ...

Which is the better option for setting a title: using .prop or .attr?

I came across a comment that mentioned The suggestion was to utilize the .prop() method instead of .attr() when setting the "title" property in jQuery versions 1.6 or newer. Could someone provide an explanation for this recommendation? ...

Exploring alternatives to ref() when not responsive to reassignments in the Composition API

Check out this easy carousel: <template> <div ref="wrapperRef" class="js-carousel container"> <div class="row"> <slot></slot> </div> <div class=&q ...

How can I filter an array by a nested property using Angular?

I need help with objects that have the following format: id: 1, name: MyObj properties: { owners: [ { name:owner1, location: loc1 }, { name:owner2, location: loc1 } ] } Each object can have a different number of owners. I' ...

Exploring the process of dynamically updating a form based on user-selected options

I need assistance with loading an array of saved templates to be used as options in an ion-select. When an option is chosen, the form should automatically update based on the selected template. Below is the structure of my templates: export interface ...

The console is showing the Ajax Get request being logged, but for some reason it is not displaying on the

Could someone please explain why this response isn't displaying on the page? $.ajaxPrefilter( function (options) { if (options.crossDomain && jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? &apos ...

Better ways to conceal notifications as soon as a new one appears with Toastr

Whenever a new notification pops up in my application, I desire for the previous one to automatically disappear. It is crucial for only one notification to be displayed at any given time. Is there a way to accomplish this using toastr? ...

Executing `console.log()` in Windows 8 using JavaScript/Visual Studio 2012

Whenever I utilize console.log("Outputting some text") in JavaScript within Visual Studio 2012 for Windows 8 metro development, where exactly is the text being directed to? Which location should I look at to see it displayed? Despite having the "Output" pa ...

Changing Images with Jquery on Click Event

This section of the HTML document contains an image link that is designed to switch between two images when clicked. The images in question are timeline-hand and hand-clicked. Clicking on the image should change it from one to the other and vice versa. Ho ...

Issue with printing JavaScript value using Selenium_ASSUME_WE_NOT have any changes in the content

I'm currently running tests with Selenium and Java. I've experienced success in printing the pages' HTML from JavaScript by using an alert: js.executeScript("alert($('html').html());"); However, when trying to use return, nothing ...

What is the best way to ensure that my program runs nonstop?

Is there a way to have my program continuously run? I want it to start over again after completing a process with a 2-second delay. Check out my code snippet below: $(document).ready(function () { var colorBlocks = [ 'skip', 'yell ...