--- name: data-fetching-best-practices description: Patterns and best practices for efficient data fetching in Nuxt --- # Data Fetching Best Practices Effective data fetching patterns for SSR-friendly, performant Nuxt applications. ## Choose the Right Tool | Scenario | Use | |----------|-----| | Component initial data | `useFetch` or `useAsyncData` | | User interactions (clicks, forms) | `$fetch` | | Third-party SDK/API | `useAsyncData` with custom function | | Multiple parallel requests | `useAsyncData` with `Promise.all` | ## Await vs Non-Await Usage The `await` keyword controls whether data fetching **blocks navigation**: ### With `await` - Blocking Navigation ```vue ``` - **Server**: Fetches data and includes it in the payload - **Client hydration**: Uses payload data, no re-fetch - **Client navigation**: Blocks until data is ready ### Without `await` - Non-Blocking (Lazy) ```vue ``` Equivalent to using `useLazyFetch`: ```vue ``` ### When to Use Each | Pattern | Use Case | |---------|----------| | `await useFetch()` | Critical data needed for SEO/initial render | | `useFetch({ lazy: true })` | Non-critical data, better perceived performance | | `await useLazyFetch()` | Same as lazy, await only ensures initialization | ## Avoid Double Fetching ### ❌ Wrong: Using $fetch Alone in Setup ```vue ``` ### ✅ Correct: Use useFetch ```vue ``` ## Use Explicit Cache Keys ### ❌ Avoid: Auto-generated Keys ```vue ``` ### ✅ Better: Explicit Keys ```vue ``` ## Handle Loading States Properly ```vue ``` ## Use Lazy Fetching for Non-critical Data ```vue ``` ## Minimize Payload Size ### Use `pick` for Simple Filtering ```vue ``` ### Use `transform` for Complex Transformations ```vue ``` ## Parallel Fetching ### Fetch Independent Data with useAsyncData ```vue ``` ### Multiple useFetch Calls ```vue ``` ## Efficient Refresh Patterns ### Watch Reactive Dependencies ```vue ``` ### Manual Refresh ```vue ``` ### Conditional Fetching ```vue ``` ## Server-only Fetching ```vue ``` ## Error Handling ```vue ``` ## Shared Data Across Components ```vue ``` ## Avoid useAsyncData for Side Effects ### ❌ Wrong: Side Effects in useAsyncData ```vue ``` ### ✅ Correct: Use callOnce for Side Effects ```vue ```