JAVASCRIPT

Asynchronous Data Fetching in Vue 3 Composition API

Learn to fetch data asynchronously using `onMounted` lifecycle hook and manage reactive state with `ref` in Vue 3's Composition API for dynamic content.

<template>
  <div>
    <h1>Posts</h1>
    <p v-if="isLoading">Loading posts...</p>
    <p v-else-if="error">Error: {{ error }}</p>
    <ul v-else>
      <li v-for="post in posts" :key="post.id">
        <h3>{{ post.title }}</h3>
        <p>{{ post.body }}</p>
      </li>
    </ul>
  </div>
</template>

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

const posts = ref([]);
const isLoading = ref(true);
const error = ref(null);

const fetchPosts = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    posts.value = await response.json();
  } catch (err) {
    error.value = err.message;
  } finally {
    isLoading.value = false;
  }
};

onMounted(() => {
  fetchPosts();
});
</script>
How it works: This snippet shows a common pattern for fetching asynchronous data in a Vue 3 component using the Composition API. It utilizes `ref` to create reactive variables for `posts`, `isLoading`, and `error` states. The `fetchPosts` async function performs the API call, handles potential errors, and updates the reactive state. The `onMounted` lifecycle hook ensures that the data fetching occurs when the component is mounted to the DOM. This setup provides clear management of loading, success, and error states for dynamic content.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs