🪴 Rhitik's Notebook

Search

Search IconIcon to open search

Last updated Dec 11, 2023 Edit Source

# Lazy API calls

Data fetching · Lazy

By default, data fetching composables will wait for the resolution of their asynchronous function before navigating to a new page by using Vue’s Suspense. This feature can be ignored on client-side navigation with the lazy option. In that case, you will have to manually handle loading state using the pending value.

app.vue

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<script setup lang="ts">
const { pending, data: posts } = useFetch('/api/posts', {
  lazy: true
})
</script>

<template>
  <!-- you will need to handle a loading state -->
  <div v-if="pending">
    Loading ...
  </div>
  <div v-else>
    <div v-for="post in posts">
      <!-- do something -->
    </div>
  </div>
</template>

You can alternatively use  useLazyFetch and useLazyAsyncData as convenient methods to perform the same.

1
const { pending, data: posts } = useLazyFetch('/api/posts')