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'

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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
      });
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.