`In which hook to call Axios to update the DOM?
A
A
Artem Mikhnevich2019-02-10 19:14:58
Vue.js
Artem Mikhnevich, 2019-02-10 19:14:58

In which hook to call Axios to update the DOM?

Pulling data through Axios:

mounted() {
   axios
      .get(`http://api.openweathermap.org/data/2.5/find?lat=${this.lat}&lon=${this.lon}&type=like&lang=ru&units=${this.measureSystem}&APPID=${this.ApiKey}`)
      .then(response => (this.dataWeather = response));
  },

And I track button changes here:

computed: {
   setMeasure () {
    if (this.toggle === 1) {
     return this.measureSystem = 'metric'
    } else {
      return this.measureSystem = 'Imperial'
    }
   }
}

The variable is changed, but the page does not render. I tried to call the request again in updated and beforeUprade, the page was rendered with a delay and a bunch of requests were called, as if I had caught recursion.
Please tell me in which life cycle hook to call Axios request, or how would it be more correct to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-02-10
@timartinov

No hooks are needed here. Set up property tracking:

watch: {
  measureSystem: {
    immediate: true,
    handler() {
      // сюда переносите код из mounted - axios.get(...)
    },
  },
},

You don't need to set values ​​in computed, make measureSystem from the regular property computed (unless, of course, it is used somewhere else besides the query shown; otherwise, you can follow toggle and calculate the value of the units parameter immediately before the query itself):
computed: {
  measureSystem() {
    return this.toggle === 1 ? 'metric' : 'Imperial';
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question