Search code examples
javascriptvue.jsmountwatch

Vue.js How to watcher before mounted() , can't get data from watch


In the async mounted() part, it can't retrieve data from this.point0 because it mounted before watch right? How can I fix this.

My goal is to update the p1 and p0 in mounted() whenever the new API is sent in watch

Can check out my code here https://jsfiddle.net/1eahf26q/

  data() {
    return {
      point0: [],
      point1: [],
    };
  },

  watch: {
   async breedKey (newVal, oldVal)  {
       try {
      this.promise = axios.get(new_url);
      const res = await this.promise;

      this.point0 = res.data.data[0].Freq;
      this.point1 = res.data.data[1].Freq;
   }
  },    

  async mounted() {
    await this.promise;

    let p0 = this.point0;
    let p1 = this.point1;
    const datapresent = [p0, p1, this.point1,];
    },
})

Solution

  • From you code, it seems like a computed would do the job. Try moving your logic from mounted() to computed as

    computed: {
        dataPreset() {
            return [this.p1, this.p2];
        }
     }
    

    This would automatically return an updated dataPreset whenever p1 or p2 change.

    EDIT:

    As far as I have understood, you can definitely initialize your graph once you have the API data inside your watcher. You watcher could be like

    watch: {
        selectedTrend: {
          immediate: true,
          handler(to) {
            this.trend = to.Trends;
            this.GetAPIData(to.Trends, to.DT);  //A method to get the sample API DATA
            this.InitializeGraph(); //A method which initializes your graph
          }
        }
      },
    

    A sample sandbox created at: https://codesandbox.io/s/twitter-trends-fp0wn