The ideal way to efficiently await retrieved data in vue.js to ensure smooth integration in another function

Is there a way to properly handle the successful fetch event before executing the loadMarkers() method? I keep encountering an error because monitorsData.monitors is undefined.

I attempted using await with fetch but I'm unsure of the correct usage.

data(){
        return{
            monitorsData:'',
            timer:'',
            loading:false,
            message:'60200950',
            markers: [],
        }
    },
    created(){
        this.searchStation()
        this.loadMarkers()
        this.timer = setInterval(this.searchStation, 50000)
    },
    methods:{
        loadMarkers(){
            for(let i = 0; i < this.monitorsData.monitors.length; i++){
                this.markers.push({id: i, position: {lat: this.monitorsData.monitors[i].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[i].locationStop.geometry.coordinates[1]}})                  
            }
        },
        searchStation(){
            this.loading=true
            var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
                targetUrl = 'http://www.wienerlinien.at/ogd_realtime/monitor?DIVA='+ this.message+ '&activateTrafficInfo=stoerungkurz'
            fetch(proxyUrl + targetUrl)
            .then(response => response.json())
            .then(jsonData => this.monitorsData = jsonData.data)
            .catch(e => console.log(e))
            this.loading = false
            this.message = ''
        },

    },


In addition, I am unsure how to address the same issue in computed properties.

    computed:{
        mapConfig() {
            return{
                ...mapSettings,
                zoom: 8,
                center: {lat: this.monitorsData.monitors[0].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[0].locationStop.geometry.coordinates[1]}
            }
        }
    },

Answer №1

Transfer the loading and message functionality into your then chain

searchStation(){
    this.loading=true
    var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
        targetUrl = 'http://www.wienerlinien.at/ogd_realtime/monitor?DIVA='+ this.message+ '&activateTrafficInfo=stoerungkurz'
    fetch(proxyUrl + targetUrl)
    .then(response => response.json())
    .then(jsonData => {
       this.monitorsData = jsonData.data
       this.loading = false
       this.message = ''
        })
    .catch(e => console.log(e))

},

You can now utilize an if statement to determine if it is still loading:

    loadMarkers(){
        if(this.loading) return; //if its true, the function will stop here
        for(let i = 0; i < this.monitorsData.monitors.length; i++){
            this.markers.push({id: i, position: {lat: this.monitorsData.monitors[i].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[i].locationStop.geometry.coordinates[1]}})                  
        }
    },

This approach should also apply to your computed property:

    mapConfig() {
        if(this.loading) return;
        return{
            ...mapSettings,
            zoom: 8,
            center: {lat: this.monitorsData.monitors[0].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[0].locationStop.geometry.coordinates[1]}
        }
    }

Answer №2

Make sure to execute the method following the completion of fetching:

searchStation(){
        this.loading=true
        var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
            targetUrl = 'http://www.wienerlinien.at/ogd_realtime/monitor?DIVA='+ this.message+ '&activateTrafficInfo=stoerungkurz'
        fetch(proxyUrl + targetUrl)
        .then(response => response.json())
        .then(jsonData => { 
           this.loading = false
           this.message = ''
           this.monitorsData = jsonData.data;
           this.loadMarkers(); // Execute the method here
         })
        .catch(e => console.log(e))
    },

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

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

Tips for working with elements in WebDriver that are created dynamically by JavaScript

As a novice in automation using Java and WebDriver, I find myself facing a particular issue: Browse for a specific customer Select a new customer type from a dropdown menu Click on the Save button Outcome: Upon trying to change the customer, a message p ...

Using Node.js to separate applications on the same URL based on different paths

We currently have a server hosting one domain, where we have placed apps separately using specific URL paths. For instance, the front-end of our app is mapped to the main URL (/). Requests to / will be directed to the front-end app, while adding /api in ...

What is the best way to reset the state to null when the input field is blank?

After setting some inputs with a state of null, I noticed that when the end-user types something and then deletes it all, the input reverts back to an empty string. How can I adjust the state so that it returns to null? I seem to be encountering an issue ...

Enhancing SVG graphics dynamically with JavaScript and ensuring compatibility across different web browsers

I am currently working on incorporating an element into an existing SVG file. Interestingly, the process runs smoothly on Chrome and Firefox but encounters issues on Edge. I aim for it to function seamlessly on the latest versions of all three browsers, wi ...

How can I identify where a Mesh and Particle System intersect in Three.js?

I have a unique setup where I have a particle system utilizing sprites, housed in an Object3D akin to the "interactive / points" example from three.js. Additionally, I have a simple sphere mesh that tracks my cursor's movements. Check out the example ...

Interactive map navigation feature using React.js

Can someone help me figure out how to create a dynamic map with directions/routes? I am currently using the Directions Renderer plugin, but it only shows a static example. I want to generate a route based on user input. Below is the code snippet: /* ...

Ways to link numerous sockets within a single Vue.js project?

import VueSocketIOExt from 'vue-socket.io-extended'; import { io } from 'socket.io-client'; const socketOne = io('http://localhost:3200/'); const socketTwo = io('http://localhost:3100/'); Vue.use(VueSocketIOExt, so ...

Performance problem with React-Native for-looping through a large array size

I'm currently facing a performance issue with the search function in my react-native app. The search involves scanning through an array of 15,000 elements for specific keywords. Surprisingly, the search performs well and quickly on Android devices, bu ...

Tips for invoking C language code from JavaScript by using the js-ctypes extension in Firefox

I need assistance with developing a Firefox extension that requires calling native C code. Here is my C program code: #include<windows.h> int add(int a, int b) { return(a + b); } And here is my JavaScript code: var {Cu} = require('chrome ...

Adding a class in Vue.js using Vee-validate if there are no errors following validation

I have created the input.vue template below. It is functioning correctly, but I am trying to figure out how to add a class when text is entered and no validation errors are present. <input v-validate="validate" v-on:input="updateValue($even ...

Error with decodeURIComponent function in Internet Explorer 8

My widget, loaded as an iframe, requires data about the hosting page. I have UTF-8 strings extracted from a page with Russian text. The page itself has proper HTML5 doctype and meta charset. This is how my code operates: params = "x1=" + encodeURICompone ...

Learn how to upload an image from Express.js to Google Cloud Storage or Firebase Storage

Currently, I am delving into the world of ExpressJS and attempting to upload an image to Firebase storage using Node. However, I encountered the error message: firebase.storage().ref() is not a function. After researching this issue, I stumbled upon this ...

The issue with `vue-meta` and `Inertia where the title appears as 'undefined' during page rendering

I'm currently working with Vue 2.6.12, Laravel, and Inertia in my project. One issue I'm facing is that when using vue-meta to modify the meta title, it briefly displays 'undefined' when loading any page. Since I am utilizing Inertia ...

User events in the fullCalendar

I'm feeling stuck. I currently have a basic fullCalendar setup for the User model in Rails. I want to add 2 buttons, allowing the User to separate the calendar into two views. One view would display only their own events, while the other would show al ...

What causes a small variation in the image composition when displaying a PNG file with drawImage?

In the code provided, the image file named "img" was created using Gimp. This image contains a color pixel : rgba=176 99 234 167. However, when displayed in a particular context and then its composition retrieved using getImageData, there is a sligh ...

Using Javascript's document.write function to modify the content of a PHP page

Here is a Javascript function that capitalizes the first letter of a string: function capitalizeFL(string) { return string.charAt(0).toUpperCase() + string.slice(1); } In a file named statuswindow.php, there are PHP scripts that use this function to ...

Troubleshooting issues with AJAX script and JSON formatted data

Here is my complete script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/E ...

How can I capture the 'ended' event from an HTML5 video tag using Ember in a controller?

I am having an issue with an hbs file that contains an html5 video tag: <video id="externalVideo" controls loop> <source src="../assets/videos/test.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> I am ...

React router will only replace the last route when using history.push

I'm working on implementing a redirect in React Router that triggers after a specific amount of time has elapsed. Here's the code I've written so far: submitActivity(){ axios.post('/tiles', { activityDate:thi ...