Data Fetching in Nuxt.js

Jul 14, 2024

Data Fetching in Nuxt.js

Composables: useFetch and useAsyncData

  • useFetch: straightforward method for data fetching.
  • useAsyncData: wraps asynchronous logic for complex calls (e.g., third-party libraries like Supabase).
  • Under the hood, useFetch = useAsyncData in most cases.
  • Helpful when making multiple API calls within a component.

Vue Suspense Component

  • Nuxt uses Vue Suspense to prevent navigation until all async functions are resolved.
  • Example: server route that fetches products from a third-party API with a 2-second delay.
  • Page example: products.vue uses useFetch to fetch and display products.

Navigation and Loading States

  • By default, delays navigation until async functions are resolved.
  • nuxt-loading-indicator: built-in component to show progress bar during navigation.
  • Opinions on UX: Default behavior (delaying navigation) not ideal for user experience.

Lazy Loading

  • Ideal to navigate immediately & show loading state while waiting for async functions:
    • Use options object with lazy property set to true.
    • Exposes pending variable to show loading state.
    • Refactor example products.vue to use lazy option.

Improving UI

  • Use Nuxt UI Library for better UI: install using command.
  • Use NuSkeleton component to create a skeleton for the layout.
  • Example: Replace product cards with 10 skeleton instances in the template.

Additional Composables

  • useLazyFetch and useLazyAsyncData: equivalents of useFetch and useAsyncData with lazy option.
  • Cleaner code if only using lazy option.
  • Note: No need for await if using lazy fetch methods, but including it doesn’t affect functionality.

Conclusion

  • Better user experience with immediate navigation & loading state.
  • lazy fetch methods and UI improvements enhance UX.
  • Recommendations for using nuxt-loading-indicator, NuSkeleton, and lazy methods.

  • Advice: leave likes on videos and subscribe for more content.