Unspecified array properties in VueJS encountered following data retrieval using axios

I am currently working on a project with VueJS where I am utilizing Axios to fetch data and store it in an array.

Below is my data object structure:

data() {
    return {
        uid: [], // Each element contains a JSON containing the node and an array containing UID and operator name
        timer: null,
        tasks: [],
        nodes: [
            'assembler',
            'device'
        ]
    }

In the created section, I am calling functions to fetch data using axios:

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

Here are my methods:

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)
    },
    fetchTasks() {
        // Console log used for testing purposes
        console.log(this.uid[0].assembler)
    }
}

The issue arises when I try to access this.uid[0].assembler, as it returns undefined even though it should contain a value. How can I resolve this?

Answer №1

fetchUID is an asynchronous function, so make sure to call fetchTasks only after fetchUID has completed execution.

created:  function() {
  // Retrieve current user ids and tasks, if available
  this.fetchUID()
  // Call this.fetchTasks() later

},
methods: {
    fetchUID() {
        var data = {}
        this.nodes.forEach(node => 
        axios.get('http://localhost:8080/' + node)
        .then(res => res.data.length > 0 ? data[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(data);
        this.fetchTasks(); // Invoke here
    },
    fetchTasks() {
        // Console log to test
        console.log(this.uid[0].assembler)


    }
}

Answer №2

After much searching, I have finally discovered the solution to the problem residing within this particular section of 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 issue lies with the forEach() method not fully compatible with async/await operations. The modified version below should resolve the issue

       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
           }
       }
    }

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

How to enhance form validations in Angular 2 using ngModelGroup

I am currently utilizing the ngModelGroup directive to consolidate multiple form inputs together. Upon reviewing the documentation (https://angular.io/docs/ts/latest/api/forms/index/NgModelGroup-directive.html), I came across the validators: any[] propert ...

Tips for defining boundaries for position absolute elements using JavaScript

Fiddle. I am in the process of developing a chat/mail application with a resizable menu similar to the Google Hangouts desktop app. When resizing the brown content pane at a normal speed, you can observe that the boundaries are functioning as intended. My ...

Persistence of query parameters from old routes to new routes using vue-router

Whenever a query parameter called userId is present in a route within my application, I want the subsequent routes to also include this query parameter. Instead of manually modifying each router-link and router.push, I am looking for a solution using rout ...

Combining multiple API requests using NodeJS

I'm currently experimenting with SteamAPI to enhance my understanding of NodeJS. My aim is to retrieve game information after making an initial request to obtain the player's profile and storing the game IDs in an array. However, I am facing a ch ...

Save the uploaded file in Express to a custom directory on the system, avoiding the project's public folder

I have successfully integrated React on the front end to upload a file and receive it in Express.js. However, when storing the file in Express, it is currently being saved in the public folder. If I need to save the files in a non-public folder located at ...

Searching for entries using an array of _id along with other possible column values

const query_id = [1,2,3,4,5,6]; const query_type = "A"; let queries = await Query.find({ _id: query_id, query_type: query_type }); The current code functions as intended, but there may be a better and more elegant way to achieve t ...

Manage and oversee Leaflet GeoJSON layers within a variable or object while incorporating incremental adjustments

As I explore this question, my goal is to store geoJson layers in a variable using a javascript loop and then utilize them on my map with a layer control panel. Take a look at the following code: myURL = [ "http://localhost:8080/geoserver/jonquiere_lo ...

Navigating within components using code is an essential skill when working with Vue Router

I am currently developing a Quasar application powered by Vue 3 with vue-router version 4 All my routes are properly configured and function well when navigating from a component template using <router-link to="/route">Go to route</rout ...

Steps for embedding the code into your website

I'm facing an issue with integrating a .jsx file into my website. I tried testing it on a single-page demo site, but nothing is showing up. Can someone guide me through the steps to successfully integrate it onto my site? I've also attached the . ...

Exploring immersive virtual reality websites with a complete full-screen 3D experience

As I work on building a virtual reality website, I find myself pondering a challenging question: how can we seamlessly transition users from experiencing one VR website in full screen stereoscopic view to another, all without disrupting their immersive e ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Create Mesh from Three.js Points

I'm attempting to create an interactive shape in Three.js by using points generated from mouse clicks. Below is the code that I currently have: mouse.x = ( ( event.clientX - renderer.domElement.offsetLeft ) / player.width ) * 2 - 1; mouse.y = - ( ( ...

Is there a way to obtain asynchronous stack traces using Node.js and TypeScript?

When working with TypeScript, I encountered an issue with stack traces. It seems that only the bottommost function name is displayed. My setup includes Node.js v12.4.0 on Windows 10 (1803). Below is the code snippet: async function thrower() { throw new ...

What is the best way to implement backup style attributes for a React JS component?

Is there a method to implement fallback style properties for a component? For example: var inlineStyle = { display: '-webkit-box', display: '-webkit-flex', display: '-moz-box', display: '-moz-flex', ...

Troubleshooting a problem with dynamic options in Materialize select set

I'm currently facing an issue with my two dependent dropdowns, country and state. When I select a country, I use JavaScript to populate the respective states in the state dropdown. However, even though the options are added correctly when I inspect th ...

Tips for detecting and handling errors in user input from the console

Is there a way to catch errors in Chrome's developer tools console when an input throws an error? I attempted using window.addEventListener("error") but it seems that the onerror event listener on window does not capture the console errors. ...

Issue with collapsed navbar button functionality in Bootstrap version 5.1.3

Issue with Bootstrap 5 Navbar Collapse Functionality The navbar collapse button is not working on my PC. The button appears but when clicked, the navbar does not show up. Surprisingly, when I test the code on Codeply (without linking to Bootstrap 5 and ot ...

Is there a way to only allow the active video to play while disabling the others in this Vue 3 and Bootstrap 5 carousel?

I'm currently developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Additionally, I'm incorporating Bootstrap 5 for the UI. To showcase movie trailers on the movie details page, I've created the ...

Redux persist isn't functioning properly as the rehydration process only happens one time

I am currently working with React version 15.4.2 and Redux, trying to persist my React/Redux state when the browser refreshes. Despite suggestions of using redux-persist, I encountered issues when following the basic instructions as the state resets to emp ...

Exploring the location.path in angularjs

Is there a way to use $location.path for redirection in angularjs? I have the configuration below: ngModule.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $urlRouterProvider. ...