Skip to content

Custom Hooks for Authenticated Data Access in React Query Application

This document explains the useAuthenticatedMutation and useAuthenticatedQuery custom hooks used in your React + React Query application.

Purpose:

  • Simplify data fetching for authenticated users by automatically including the access token in requests.
  • Provide consistent error handling and token refresh mechanisms.

useAuthenticatedMutation:

  • Used for making authenticated mutations (data updates) using React Query.
  • Accepts:
    • queryKey: Unique identifier for the mutation within React Query.
    • queryFn: Function responsible for making the actual API request, taking the access token and optional parameters.
    • config: Optional configuration options for the mutation, including error handling and retry logic.
  • Retrieves the access token from React Query's global state or cookies.
  • Passes the access token and any provided parameters to the queryFn.
  • Handles errors and refetches data if necessary based on error codes or token expiration.

useAuthenticatedQuery:

  • Used for making authenticated queries (data fetching) using React Query.
  • Accepts:
    • queryKey: Unique identifier for the query within React Query.
    • queryFn: Function responsible for making the actual API request, taking the access token and optional parameters.
    • config: Optional configuration options for the query, including caching and refetching behavior.
  • Retrieves the access token from React Query's global state and optionally cookies (as a fallback).
  • Disables the query if no access token is found.
  • Includes the access token in the request made by queryFn.
  • Handles errors and refetches data if necessary based on error codes or token expiration.

Benefits:

  • Improved code reuse and readability by abstracting out token handling.
  • Enhanced security by ensuring access tokens are included in authorized requests.
  • Streamlined error handling and token refresh logic.

Additional Notes:

  • These hooks rely on the presence of a common.KEY_ACCESS_TOKEN constant in your project to identify the access token.
  • The hooks leverage React Query's built-in mechanisms for error handling and refetching, providing a consistent approach.
  • Consider reviewing the implementation details of these hooks for a deeper understanding.