Blog>
Snippets

Data fetching with lifecycle hooks

Contrast the approach of fetching data within the created hook in Options API versus the setup function in Composition API.
// Options API approach

new Vue({
  el: '#app',
  data() {
    return {
      items: []
    };
  },
  created() {
    // Data fetching would generally happen here
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => {
        this.items = data;
      })
      .catch(error => console.error('Error fetching data:', error));
  }
});
In the Options API approach, the 'created' lifecycle hook is used to fetch data as soon as the Vue instance is created. The 'this' context refers to the Vue instance itself, allowing the fetched data to be assigned directly to the 'items' data property.
// Composition API approach

import { ref, onMounted } from 'vue';

export default {
  setup() {
    const items = ref([]);

    onMounted(async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        items.value = await response.json();
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    });

    return {
      items
    };
  }
};
In the Composition API, the setup function is executed before the component is created. The 'onMounted' lifecycle hook is used instead to ensure the DOM has been mounted before fetching data. The 'ref' function creates a reactive reference for data that updates the template when changed.