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

Is there a way to connect either of two distinct values in Angular?

Looking to assign the data with two possible values, depending on its existence. For instance, if I have a collection of TVs and I want to save the "name" value of myTVs[0] and myTVs[1]. For example: var myTVs = [ { "JapaneseTV": { ...

Executing a JavaScript function within PHP code

I am working on a foreach loop that creates a series of checkboxes with items from a database. Currently, none of the checkboxes are pre-checked and each time a user checks one, a JavaScript function is called. Now, my clients want the first checkbox to b ...

"Counting the clicks on the filter button in React

I have: var RightPanel = React.createClass({ componentDidMount: function () { this.load(); }, load: function(){ }, render: function () { return ( <div> <div className="row"> ...

How can I use jQuery to hide each div of the same class individually when a user clicks on each div to close

I am working on a project where I have multiple notification boxes represented by divs with the same class. These boxes are set to fade in one after the other using jQuery. Each box also contains a 'close_box' div that acts as a button to close/h ...

How can I effectively assign model data to a service property in an AngularJS controller?

I have established a service to facilitate the sharing of data/state across multiple controllers. One of the controllers updates certain properties within the service using scope data through a save function. The updated data is then accessed by other cont ...

Fontawesome is unable to update the class due to the presence of invalid characters in the string

const toggleDarkOrLight = document.getElementsByTagName('i')[0]; var toggled = false; const toggleFunction = () => { if (toggled === false) { toggleDarkOrLight.classList.remove('fa fa-toggle-off'); toggleDarkOrLight.classLi ...

Creating a CSS animation to slide a div outside of its container is

I currently have a flexbox set up with two adjacent divs labeled as DIV 1 and DIV 2. By default, both DIV 1 and DIV 2 are visible. DIV 2 has a fixed width, occupying around 40% of the container's width. DIV 1 dynamically adjusts its width to ac ...

From transforming nested JSON into flat JSON structures within Javascript

Currently, I am faced with a challenge in my JavaScript programming. The task at hand is to transform the JSON data obtained from an API into a different structure while maintaining the essence of the original JSON. The existing JSON comprises members, num ...

fetching indexeddb information using the equivalent of a "WHERE IN (a,b)" query

I've been working on transitioning from websql to indexeddb, but I'm struggling to recreate the SELECT query: "SELECT * FROM tableA WHERE cid ='"+cid+"' AND hid IN("+hid+",1) ORDER BY hid DESC LIMIT 1"; function getMyData(e) { var ...

How should I proceed if I encounter an npm error stating that cb() was never called?

Hey everyone. I keep encountering an issue with npm whenever I attempt to install packages. I am receiving the following error message: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <h ...

The onclick event for a Bootstrap .btn-group checkbox functions correctly in JSFiddle, but encounters issues when tested

The toggle button group in the form below utilizes Bootstrap and checkboxes. I am looking to track click events on the checkbox inputs. <html> <head> <title>Example: Bootstrap toggle button group</title> <meta charset="UTF-8 ...

Shut down the angular modal

I am currently learning AngularJS and I find myself working on an application that utilizes both angular modal and jqGrid. (I understand this may not be the ideal setup, but for now, I have to make it work with both.) The content of my modal is loaded usi ...

The filter function in Material UI data grid does not seem to be functioning properly when using the renderCell method

I'm currently working on a react project that includes a Data Grid. While the filter functionality works well with most fields, it seems to be having issues with the field that utilizes renderCell. Is there a way to enable filtering for the movie titl ...

When using a variable to fetch data in JSON, an undefined error occurs. However, if a hardcoded index

I am facing an issue while trying to extract and manipulate JSON data from a file for an application I am developing. When looping through the data, I encounter an undefined error that seems to indicate a missing property in the JSON object when accessing ...

What is the best approach for managing the Paste event (using Ctrl+v or mouse) in vue.js?

When content is pasted into a text area in my vue.js application, I would like to trigger a function. Which event should I use for this scenario? ...

Can you explain the significance of "=>" in a context other than function invocation?

Working my way through the freeCodeCamp JavaScript course has left me quite puzzled about arrow functions. I know how to write a function using arrow notation, like this: const myFunc = () => "value"; However, in one of the later challenges, ...

Updating a dataview inside a Panel in extjs 3.4

I am facing an issue with my extjs Panel component that includes a dataview item. Initially, it works perfectly fine in displaying images from a store. However, upon reloading the imgStore with new image URLs (triggered by a user search for a different cit ...

Activating the change event in jQuery: A step-by-step guide

Within my ASP.NET page, I have included a UserControl that contains a RadioButtonList. Whenever an item in the RadioButtonList is changed, I need to trigger the following jQuery function: $('#rdlUser').change(function (e) { alert("change fun ...

During model update, AngularJS experienced a loss of CSS class in DOM re-rendering

My challenge involves managing a table that dynamically updates via WebSocket messages, causing the selection state to be lost. The rows in this table loop through model data, and upon clicking a cell, all cells in the same row toggle to have an .active cl ...

Styling Process Steps in CSS

Just starting out with CSS! I'm looking to replicate the Process Step design shown in the image. https://i.stack.imgur.com/Cq0jY.png Here's the code I've experimented with so far: .inline-div{ padding: 1rem; border: 0.04rem gray ...