← Back to Vue.js Course | Chapter 9: Composables & Composition API | Lesson 7 of 7

Async Composables का उपयोग

Composables asynchronous work wrap कर सकते हैं, data, loading, और error refs expose करते हुए जो request आगे बढ़ने के साथ update होते हैं।

In this page:

  1. Async Composables
Syntax
markup
export function useFetch(url) {
  const data = ref(null);
  const error = ref(null);
  const loading = ref(true);
  fetch(url)
    .then((r) => r.json())
    .then((d) => (data.value = d))
    .catch((e) => (error.value = e))
    .finally(() => (loading.value = false));
  return { data, error, loading };
}

Async Composables

एक typical useFetch composable data, error, और loading refs hold करता है, call होने पर या इसका URL बदलने पर request शुरू करता है और खत्म होने पर refs update करता है। Components बस refs पढ़ते हैं, और यह pattern repeated loading और error code हटा देता है।

Note: error case handle करें और एक finally block में loading reset करें।

उदाहरण: Async composables

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <p v-if="loading">Loading...</p>
  <p v-else-if="error">Error: {{ error }}</p>
  <p v-else>User: {{ data.name }}</p>
</div>
<script>
  function useAsync(fn) {
    const data = Vue.ref(null), error = Vue.ref(null), loading = Vue.ref(true);
    fn().then((r) => (data.value = r)).catch((e) => (error.value = e.message)).finally(() => (loading.value = false));
    return { data, error, loading };
  }
  Vue.createApp({
    setup() {
      return useAsync(() => new Promise((resolve) => setTimeout(() => resolve({ name: "Ada" }), 20)));
    },
  }).mount("#app");
  console.log("at start:", document.querySelector("p").textContent);
  setTimeout(() => console.log("after load:", document.querySelector("p").textContent), 100);
</script>
</body>
</html>

<!-- Output:
Rendered: User: Ada
console: at start: Loading...
console: after load: User: Ada
-->
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. loading state भूल जाना
  2. errors handle न करना
  3. URL जल्दी बदलने पर requests race करना
चैप्टर सारांश
  • data, error, और loading refs expose करें
  • promise settle होने पर refs update करें
  • Failures handle करें
  • Components में reuse करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.