useRequest.ts


Overview

useRequest.ts is a custom React hook that integrates the HTTP client library Axios with the React data fetching hook SWR to simplify and standardize API requests in React applications. It provides an easy-to-use interface for making HTTP requests, handling loading and error states, caching, and revalidation with minimal boilerplate code.

This hook abstracts the complexity of combining Axios and SWR by:


Detailed Explanation

Types and Interfaces

GetRequest

type GetRequest = AxiosRequestConfig | null

Return<Data, Error>

interface Return<Data, Error> extends Pick<
  SWRResponse<AxiosResponse<Data>, AxiosError<Error>>,
  'isValidating' | 'error' | 'mutate'
> {
  data: Data | undefined;
  response: AxiosResponse<Data> | undefined;
}

Config<Data, Error>

export interface Config<Data = unknown, Error = unknown> extends Omit<
  SWRConfiguration<AxiosResponse<Data>, AxiosError<Error>>,
  'fallbackData'
> {
  fallbackData?: Data;
}

useRequest Hook

function useRequest<Data = unknown, Error = unknown>(
  request: GetRequest,
  { fallbackData, ...config }: Config<Data, Error> = {}
): Return<Data, Error>

Implementation Details


Usage Example

import useRequest from './useRequest'

interface User {
  id: number;
  name: string;
}

function UserProfile({ userId }: { userId: number }) {
  const { data, error, isValidating, mutate } = useRequest<User>(
    {
      url: `/api/users/${userId}`,
      method: 'GET'
    },
    {
      fallbackData: { id: 0, name: 'Loading...' }
    }
  );

  if (error) return <div>Error loading user.</div>;
  if (isValidating) return <div>Loading...</div>;

  return (
    <div>
      <h1>User Profile</h1>
      <p>ID: {data?.id}</p>
      <p>Name: {data?.name}</p>
      <button onClick={() => mutate()}>Refresh</button>
    </div>
  );
}

Interaction with Other System Components


Important Implementation Notes


Visual Diagram

flowchart TD
    A[useRequest Hook]
    A -->|accepts| B[GetRequest (AxiosRequestConfig | null)]
    A -->|accepts| C[Config (SWRConfiguration + fallbackData)]
    A --> D[useSWR]
    D -->|key| B
    D -->|fetcher| E[axios.request(request)]
    E -->|response| D
    D -->|returns| F{SWRResponse}
    F -->|data| G[AxiosResponse<Data>]
    F -->|error| H[AxiosError<Error>]
    F -->|isValidating| I[boolean]
    F -->|mutate| J[function]
    A -->|returns| K[Return<Data, Error>]
    K -->|data| L[Data | undefined]
    K -->|response| G
    K -->|error| H
    K -->|isValidating| I
    K -->|mutate| J

Summary

useRequest.ts provides a robust, type-safe React hook for data fetching that leverages Axios for HTTP requests and SWR for client-side caching and revalidation. It streamlines API communication in React apps, supporting fallback data, error handling, and advanced cache control, making it a valuable utility for scalable frontend development.