I'm currently working on a feature that involves fetching data from a URL that changes every time a user chooses a new value from a <select>
dropdown. The fetched data updates the songkickData
array with the latest information. However, when I check the songkickData
array using console.log after each <select>
change, it displays data from the previous selection instead of the current one.
I suspect that the issue lies in the timing of when the code is executed, synchronicity, or possibly promises, but I haven't fully grasped these concepts yet.
Below is the code snippet:
<template>
<select v-model="selected" @change="getCityData">
<option v-for="city in cities" :key="city.id" :value="city.id">{{ city.label }}</option>
</select>
</template>
import cityData from "../data/songkickCityData.js"
export default {
data() {
return {
cities: cityData,
songkickData: []
}
},
methods: {
getCityData(e) {
const songkickCityId = e.target.value
let songkickUrl = this.getSongkickUrl(songkickCityId)
fetch(songkickUrl)
.then(res => res.json())
.then(data => this.songkickData = data)
this.getRandomGig()
},
getSongkickUrl(songkickCityId) {
const now = new Date()
const today = now.toISOString().slice(0, 10)
const songkickAPIKey = 'XXXXXXXXXXXXX'
let songkickUrl = `https://api.songkick.com/api/3.0/metro_areas/${songkickCityId}/calendar.json?min_date=${today}&apikey=${songkickAPIKey}`;
return songkickUrl
},
getRandomGig() {
// I need to ensure that the data fetched is based on the current select value and not the previous one.
console.log(this.songkickData)
}
}
}