Custom Fetch Logic & Repository Pattern

Jul 12, 2024

Custom Fetch Logic & Repository Pattern

Introduction

  • Building custom fetch logic and repository pattern
  • Improves usage of useFetch vs #fetch
  • Link to previous video on useFetch misuse

Demo Application Overview

  • Simple Nuxt config with an index page
  • Initial simple fetch from JSON placeholder API
  • Introduction to useAsyncData

Repository Pattern Implementation

Basic Setup

  • Create a repository in the utils file
  • Implement get function in the repository to return a promise with dollarFetch

TypeScript Integration

  • Define types for user data
  • Ensure type completion for API responses

Custom Fetch Instance

  • Instantiate repository with a custom fetch instance
  • Import and use NitroFetchRequest and dollarFetch
  • Pass custom fetch instance during repository initialization

Creating Custom Fetch Instance

Base URL

  • Set base URL for fetch instance
  • Ability to globally provide fetch instance using plugins

Nuxt Plugin Example

  • Create a Nuxt plugin (e.g., plugins/api.ts)
  • Define custom fetch instance using runtime config
  • Use interceptors for request/response handling
  • Provide global instance to the Nuxt application

Integration with Repository

  • Pass custom fetch instance to the repository
  • Use useNuxtApp composable to access provided instance
  • Ensure full type safety

Best Practices

  • Avoid using useAsyncData in repository pattern
  • Keep repository pattern low-level, use basic fetch API
  • Use repositories for different actions independently (e.g., buttons, SSR)
  • Maintain type safety end-to-end
  • Classes in repository should not be serialized to avoid errors

Conclusion

  • Repository pattern offers cleaner, more modular code
  • Custom fetch instances allow for varied configurations (e.g., authentication)
  • Segregate repository logic from view context for clarity
  • Preview for upcoming videos on new Nuxt plugin syntax and parallel execution

Resources

  • Links to code and related videos in the description