Skip to content

Commit

Permalink
Introduce the useAsyncData() sample code (with API endpoint)
Browse files Browse the repository at this point in the history
  • Loading branch information
LSViana committed Oct 28, 2024
1 parent 7076f0e commit 14464b5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
13 changes: 11 additions & 2 deletions pages/experiments/data-fetching/nuxt/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@
<p><code>useFetch()</code> = <code>{{ useLazyFetchResponse.data.value?.value ?? 0 }}</code></p>
</WlExperimentCanvas>
<h2 class="mt-3 text-lg"><code>useAsyncData()</code></h2>
<code>WIP</code>
<p>Allows loading data asynchronously and passing it from the server to the client:</p>
<WlExperimentCanvas>
<p><code>useAsyncData()</code> = <code>{{ useAsyncDataResponse.data.value }}</code></p>
</WlExperimentCanvas>
<h2 class="mt-3 text-lg">Server-sent Events</h2>
<p>Streaming data from the server using <code>EventSource</code> in the API routes:</p>
<WlExperimentCanvas>
Expand All @@ -50,7 +53,7 @@
<script lang="ts" setup>
import { reactive } from 'vue'
import { useFetch, useLazyFetch } from '#app'
import { useAsyncData, useFetch, useLazyFetch } from '#app'
import WlButton from '~/components/experiments/forms-input/buttons/WlButton.vue'
import WlExperimentCanvas from '~/components/shared/experiments/WlExperimentCanvas.vue'
import WlContainer from '~/components/shared/layout/WlContainer.vue'
Expand All @@ -62,6 +65,12 @@ const useFetchResponse = await useFetch('/api/data-fetching/nuxt/use-fetch')
// Works when `await` is used, and it's a client-side navigation.
const useLazyFetchResponse = await useLazyFetch('/api/data-fetching/nuxt/use-lazy-fetch')
// Add timeout to simulate.
const useAsyncDataResponse = await useAsyncData(
'use-async-data',
() => new Promise(resolve => setInterval(() => resolve(3), 0))
)
const data = reactive({
sse: [] as string[]
})
Expand Down
3 changes: 2 additions & 1 deletion server/api/data-fetching/nuxt/use-lazy-fetch.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { defineEventHandler } from 'h3'
export default defineEventHandler(async () => {
console.log(`[${new Date().toISOString()}] API - useLazyFetch`)

await new Promise(resolve => setTimeout(resolve, 2000))
// Add timeout to simulate.
await new Promise(resolve => setTimeout(resolve, 0))

return {
value: 2
Expand Down

0 comments on commit 14464b5

Please sign in to comment.