[Vuejs]-How to properly wait for fetched data in vue.js for proper usage in another method

0👍

Move your loading and message 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))

},

Ok now you can use an if statement to check if its 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]}})                  
        }
    },

Should work for your computed property too:

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

0👍

You can call the method after fecth finalize:

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(); // Call method here
         })
        .catch(e => console.log(e))
    },

Leave a comment