Access data in created() to be called on mounted()

Hello everyone, i want to ask can i access data in created() to be called on mounted().
This is example code that i made .

<script>
  export default {
    data() {
      baseTime : ''
    },
    created() {
       this.$http.get(`payment`)
        .then((result) => {
            this.baseTime = result.data;
        }).catch((error) => {
            if (error.response) {
            this.errors.status = error.response.data.meta.code;
            this.errors.code = error.response.status;
            this.errors.headers = error.response.headers;
            }
        });
    },
    mounted() {
      alert(this.baseTime)
    }
  }
</script>

But alert doesn’t display data, it only display null data. Is the method that i made wrong ? . Or is there a better away to write it ?

Thank you.

Hi. I guess the this.$http.get’s promise isn’t resolved yet then mounted is run. Why can’t you move the code to mounted?

Like this ?

<script>
  export default {
    data() {
      baseTime : ''
    },
    mounted() {
       this.$http.get(`payment`)
        .then((result) => {
            this.baseTime = result.data;
        }).catch((error) => {
            if (error.response) {
            this.errors.status = error.response.data.meta.code;
            this.errors.code = error.response.status;
            this.errors.headers = error.response.headers;
            }
        });
    }
  }
</script>

i plan to call data outside of $http response but the alert still doesn’t bring up data. Is it true that i can only call data in response ?

Hi

What happens is that:
created() runs
mounted() runs and the $http.get is started but the rest of mounted() runs and completes. Not until $http.get gets a result back or fails will the functions inside then() or catch() be run. But in your template will the reactivity of vue rerender where the data is used then it changes. So if you have something like this in your template:

<template>
  ...
  <div>The basetime is {{ baseTime }}</div>
 ...
</template>

will it first show the initial value of baseTime but as soon as the request comes back will it set baseTime to a new value and this part of the component is redrawn. The problem with the alert is that it runs at once before the data is set and therefore it is null. So if you really want to run the alert after the data changes you can either put it inside the then() function or make a watcher (https://vuejs.org/v2/guide/computed.html#Watchers) for baseTime which is run when the value changes.

1 Like

oh okay i understand. Thank you for wanting to explain it. This works now in my code. Thank you very much @johandalabacka .

1 Like