Petar Yakov
Petar Yakov

Reputation: 179

Vue.js component loads before axios.get()

I have the following component with a prop called objects

<Table :objects="orders"/>

And in mounted() I have an axios.get() that fetches data from Directus CMS that looks like this.

this.orders = await this.axios.get('url')
    .then(response => {
        return response.data.data;
     });

I get an error in my table component saying that the objects prop is null or undefined, but in Vue Devtools it has some objects in it. I tried making the axios.get() in the beforeCreated() but it still doesn't work.

Upvotes: 0

Views: 905

Answers (3)

Tim
Tim

Reputation: 391

You should not be using the data object 'orders' for your axios call. I'm assuming you are using the Options API due to your usage of 'this', otherwise I would suggest using ref() or reactive() to update the DOM. In your case, the content is rendering faster than the network response, which is why it shows undefined. You would need to fire your request in a 'beforeRouteEnter()' hook, not 'beforeCreated'.

Consider using this example instead...

export default {
  data() {
    return {
      orders: [],
    };
  },
  methods: {
    async getOrders() {
      const response = await axios.get("url");
      this.orders = response.data.data;
    },
  },
  mounted() {
    this.getOrders();
  },
};

Upvotes: 0

Nikola Gava
Nikola Gava

Reputation: 404

mounted lifecycle method happens after the component has been mounted, aka when DOM tree has already been created.

What you're looking for is beforeMount method, which is called after the component has finished setting up reactive state, but DOM nodes haven't been created yet.

If you call your endpoint inside beforeMount method and await for results, your component will render when the data already exists, on condition that no error was returned.

Upvotes: 0

3tw
3tw

Reputation: 136

I am going to assume that this.orders is an array of objects. In that case, you can simply use v-if on Table to mount the component only when this.orders contains some items.

<Table v-if="orders.length" :objects="orders"/>

You could also define the default value for prop objects: this way it won't be null even if the data is missing.

// Inside Table component
objects: {
  type: Array,
  required: false,
  default: () => [], // default value is an empty array
}, 

Upvotes: 1

Related Questions