vue.js logo

Using Suspense for Async Components


Step 1: Create an Asynchronous Component

In your Vue project, create a new file for your composable. For instance, create a file named useApi.js in a composables directory. This composable will be responsible for fetching data from an API and managing its state.


<template>
        <div>
          <h1>User Profile</h1>
          <p>Name: {{ userProfile.name }}</p>
          <p>Email: {{ userProfile.email }}</p>
        </div>
      </template>

      <script>
      import { ref, onMounted } from 'vue';

      export default {
        setup() {
          const userProfile = ref(null);

          async function fetchUserProfile() {
            const response = await fetch('https://api.example.com/user');
            userProfile.value = await response.json();
          }

          onMounted(fetchUserProfile);

          return { userProfile };
        }
      }
      </script>

Step 2: Use Suspense in Your Main Component

Now, integrate the composable into a Vue component. Create or modify a Vue component to use the useApi composable.


<template>
        <div>
          <Suspense>
            <template #default>
              <UserProfile />
            </template>
            <template #fallback>
              <div>Loading user profile...</div>
            </template>
          </Suspense>
        </div>
      </template>

      <script>
      import UserProfile from './components/UserProfile.vue';

      export default {
        components: {
          UserProfile
        }
      }
      </script>

Conclusion

By using Suspense, you have added an elegant handling of asynchronous components in your Vue application. This setup helps in managing loading states and error handling in a more declarative and organized manner. Suspense is particularly useful in scenarios where components need to wait for data before rendering, improving the user experience by providing a fallback content during the loading process.