Mikhail Krivosheev
Mikhail Krivosheev

Reputation: 569

Why is this lifecycle hook code working twice?

There is such a code:

<template>

   <div class="wrapper">
   </div>

</template>

<script>

import axios from 'axios';

export default{

  created () {
    console.log('222');
    this.getTrackerIdData();
    this.getTrackerData();
  },

  methods: {

    getTrackerIdData () {
        return axios.get("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking_new.create" , {
         })
        .then(response => {
          this.$store.commit('tracker/setTrackingKeyId', response.data.data.tracking_new_key_id);
          this.$store.commit('tracker/setQrCodeUrl', response.data.data.filename_qr_code_tracking_new);
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    getTrackerData () {

        setInterval(()=>myTimer(this), 60000);

        function myTimer(th) {
             return axios.get("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=get_tracking_data&key_id=" + th.$store.state.tracker.trackingKeyId , {
             })
            .then(response => {
              th.$store.commit('tracker/setTrackingServerData', response.data.data.tracking_data);
            })
            .catch(function (error) {
              console.log(error);
            });
        }

},

  }
}
</script>


When starting such a solution in the project, the server-side developer informed me that at least the request method getTrackerIdData () on its side works twice!
Having placed the code (console.log ('222');) in the hook of the created lifecycle (where the method calls), I found that it is displayed twice in the firebug:

введите сюда описание изображения


Question:
Why is this happening and what approach is right in this case from the point of view of the implementation of receiving data from the server?

P.S. If everything is called in the mounted hook, then the code works, including on the server side, only 1 time.

Upvotes: 2

Views: 883

Answers (1)

Mahamudul Hasan
Mahamudul Hasan

Reputation: 2823

It is important to know that in any Vue instance lifecycle, only beforeCreate and created hooks are called both from client-side and server-side. All other hooks are called only from the client-side.

so thats why created hook called 2 times and executing the console.log ('222'); twice

for reference you can read from here

Upvotes: 5

Related Questions