Blog>
Snippets

Handling reactivity with async components

Illustrate how to handle reactivity in asynchronous components, ensuring that state remains reactive after data is fetched.
<div id='app'>
  <h1>User Profile</h1>
  <p v-if='loading'>Loading...</p>
  <p v-else>{{ userProfile.name }}</p>
</div>
This is the HTML structure with Vue-directives that conditionally shows either a loading message or the user's name once it's loaded. The 'app' div is the mount point for the Vue application.
const app = new Vue({
  el: '#app',
  data: {
    userProfile: {},
    loading: true
  },
  created: function() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      try {
        const response = await fetch('/api/user-profile');
        this.userProfile = await response.json();
      } catch(error) {
        console.error('Error fetching user profile:', error);
      } finally {
        this.loading = false;
      }
    }
  }
});
This is the Vue instance that binds to the div with id 'app'. It defines a 'userProfile' data property that is updated when 'fetchData' successfully retrieves the user profile. The 'loading' data property is used to track the loading state.
<style>
  #app {
    font-family: 'Arial', sans-serif;
  }
</style>
CSS styles for the Vue application mount point to use Arial font for demonstration purposes.