0

I want to access data object in mounted hook, but when I try to access the data it will throw undefine in the console.

This is my source code

export default {

data() {
  return {
    channel: {},
    subscription: {},

  }

},

methods: {

  read() {
    axios.get('/api/get/details').then(({ data }) => {
      this.channel= data;

    })
      .catch((err) => console.error(err));
  },
},



  mounted() {

      this.read();

      console.log(this.channel.data.userid)

      fetch("https://url/v1/launch/1/details")
        .then(response => response.json())
        .then(json => {
          this.subscription = json
        });


    }

  }

but when I console this.channel.data.userid I gat 'undefine'

  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Estus Flask May 07 '20 at 17:27

2 Answers2

1

Your code is asynchronous, you meaning that console.log does not wait until this.read() is finished. Changing it to the following should work.

export default {

data() {
  return {
    channel: {},
    subscription: {},

  }

},

methods: {

  async read() {
    const { data } = await axios.get('/api/get/details')
    this.channel = data;
  },
},



  async mounted() {

      await this.read();

      console.log(this.channel.data.userid)

      fetch("https://url/v1/launch/1/details")
        .then(response => response.json())
        .then(json => {
          this.subscription = json
        });


    }

  }

Read up more on async and Promise

A. L
  • 11,695
  • 23
  • 85
  • 163
0

You are having a synchronous problem. Make your functions asynchronous and wait to end it.

export default {

  data() {
    return {
      channel: {},
      subscription: {},
    }
  },

  methods: {

    async read() {
      await axios.get('/api/get/details').then(({ data }) => {
        this.channel= data;
      })
      .catch((err) => console.error(err));
    },
  },

  async mounted() {

      await this.read();

      console.log(this.channel.data.userid);

      fetch("https://url/v1/launch/1/details")
        .then(response => response.json())
        .then(json => {
          this.subscription = json
      });
  }
}
Hans Felix Ramos
  • 4,264
  • 3
  • 16
  • 40