#Can't lazy load fetch
3 messages · Page 1 of 1 (latest)
Based on the code you've provided and the information from the knowledge sources, I can see why you're experiencing this issue. Let me explain the problem and provide a solution.
The issue is that you're using useFetch without properly handling its lazy loading capabilities. Even though you intended to use lazy fetching, the way it's currently implemented is still blocking.
To fix this and properly implement lazy loading, you should use useLazyFetch instead of useFetch. Here's how you can modify your code:
<template>
<p>Recent games</p>
<ul v-if="status === 'pending'">
Loading...
</ul>
<ul v-else>
<!-- Your list items here -->
</ul>
</template>
<script setup lang="ts">
const config = useRuntimeConfig();
const route = useRoute();
const { data, status } = useLazyFetch(`${config.public.apiBase}replays/${route.params.player}`);
</script>
By using useLazyFetch, you're telling Nuxt to start the data fetching process but not to block navigation or rendering while waiting for the data Docs > API > Composables > useLazyFetch (https://nuxt.com/docs/api/composables/use-lazy-fetch). This composable is specifically designed to trigger navigation immediately, before the async handler is resolved.
Additionally, you should handle the loading state in your template. The status variable returned by useLazyFetch can be used to show a loading indicator while the data is being fetched.
Remember that when using useLazyFetch, you need to handle the 'pending' and 'error' states directly within your component's template Docs > Getting Started > Data Fetching (https://nuxt.com/docs/getting-started/data-fetching#lazy).