Reputation: 200
I am creating an app where you can fill in your availability. You can do this by the month. Every time you change the month and you changed something the app will ask if you want to save your changes.
This is the full file https://pastebin.com/6FTuPhrV but I try to explain the problem in more detail.
When changing months I clear the days array:
getDays () {
// Clear days so it can be refilled
this.days = []
// Month and year for the days
const month = this.currentDate.month()
const year = this.currentDate.year()
const names = Object.freeze(
['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'])
const date = new Date(year, month, 1)
let fullDate = ''
while (date.getMonth() === month) {
fullDate = date.getDate() + '-' + month + '-' + year
this.days.push({
day: date.getDate(),
name: names[date.getDay()],
fullDate: fullDate
})
date.setDate(date.getDate() + 1)
}
But then the values don't reset when changing months as you can see in this image
But it does work when I put an timeout on the function that sets the days:
getDays () {
// Clear days so it can be refilled
this.days = []
// Month and year for the days
const month = this.currentDate.month()
const year = this.currentDate.year()
const names = Object.freeze(
['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'])
const date = new Date(year, month, 1)
let fullDate = ''
setTimeout(() => {
while (date.getMonth() === month) {
fullDate = date.getDate() + '-' + month + '-' + year
this.days.push({
day: date.getDate(),
name: names[date.getDay()],
fullDate: fullDate
})
date.setDate(date.getDate() + 1)
}
}, 500)
}
As seen in these images it now correctly resets the time on the days:
November days December days correctly reset.
Of course it works now but I don't want a race condition in my code and let the user wait.
Have any of you experienced the same problem? How did you solve it?
Upvotes: 2
Views: 1376
Reputation: 283
Instead of a timeout you can use this.$nextTick([callback, context])
.
A callback that executes after the next DOM update cycle.
Just place your while loop inside of the callback.
More info here: https://v2.vuejs.org/v2/api/#Vue-nextTick
Upvotes: 1