[Vuejs]-Filter, forEach and Push methods not working on Array in Vue prop

1👍

After some more troubleshooting I have finally gotten the code to work.
Special thanks to @TylerRoper for pointing out that the problem has something to do with the code being asynchronous.
I have assumed that Vue lifecycle hooks are also used for asynchronous operations, however this is not the case.

I solved the problem by adding watch properties:

  watch: {
topics: function (val) {
  this.topReady = true;
  if(this.topReady && this.secReady){
    this.allReady = true
  }
},
sections: function (val) {
  this.secReady = true;
  if(this.topReady && this.secReady){
    this.allReady = true
  }
},
allReady: function (val) {
  return this.loadPreview()
}

And updated the data accordingly:

  data() {
return {
  courseTitle: null,
  sections: [],
  topics: [],
  selected: undefined,
  topReady: false,
  secReady: false,
  allReady: false
}

and wrote the actions in a method called by one of the watch properties:

    loadPreview() {
  // Set previewSpecs
  let preview = this.topics.filter(top => this.previewSpecs.topic_id==top.topic_id)
  let previewSotId = preview[0].sectionOfTopic_id
  let previewSec = this.sections.filter(sec => sec.section_id==previewSotId);


  this.selected = previewSotId;
  this.choose(preview[0].topic_id, false, preview[0].sectionOfTopic_id, previewSec[0].data.name)
}

It all works now. Thank you to everybody who helped me sort out my first ever question on Stack Overflow!

If someone finds a better way to solve the issue, I am looking forward to your alternative.

👤aside

Leave a comment