[Vuejs]-VueJS: Properties of array undefined after fetching data with axios

0👍

I’ve finally found the answer, the issue lies in this part of the code

fetchUID() {
    var obj = {}
    this.nodes.forEach(node => 
    axios.get('http://localhost:8080/' + node)
    .then(res => res.data.length > 0 ? obj[node] = [res.data[0].id, res.data[0].operator.name] : console.log("No data found for " + node + 
    ". It seems there is no instance of " + node))
    .catch(err => console.log(err))
    )
    this.uid.push(obj)
}

The problem is the forEach() as it doesn’t really work with async/await. This should do the trick

       async fetchUID() {
       for(let node of this.nodes) {
           try  {
               const { data } = await axios.get(`http://localhost:8080/${node}`);
               if(data.length > 0)
                this.uid[node] = [data[0].id, data[0].operator.name];
               else
                console.log(`No data found for ${node}. It seems there is no instance of ${node}`)
           } catch (error) {
               // error handling
           }
       }
    }

0👍

fetchUID is async so execute fetchTasks after completing execution of fetchUID

created:  function() {
  // Get current uids and tasks, if there are any
  this.fetchUID()
  // this.fetchTasks() to be executed later

},
methods: {
    fetchUID() {
        var obj = {}
        this.nodes.forEach(node => 
        axios.get('http://localhost:8080/' + node)
        .then(res => res.data.length > 0 ? obj[node] = [res.data[0].id, res.data[0].operator.name] : console.log("No data found for " + node + 
        ". It seems there is no instance of " + node))
        .catch(err => console.log(err))
        )
        this.uid.push(obj);
        this.fetchTasks(); // Execute here
    },
    fetchTasks() {
        // console log for testing
        console.log(this.uid[0].assembler)


    }
}

Leave a comment