Rehooks

useFetch

Fetches data from a specified API endpoint.

useFetch

Installation

npx rehooks-cli@latest add useFetch

Usage

Component.tsx
import { useFetch } from "~/hooks/useFetch";
 
type User = {
  id: number;
  name: string;
  email: string;
};
 
type ApiError = {
  message: string;
};
 
function Component() {
  const { data, error, isPending, isSuccess, isError, refetch } = useFetch<
    User[],
    ApiError
  >("https://jsonplaceholder.typicode.com/users", {
    method: "GET",
  });
 
  return (
    <div>
      <h1>User List</h1>
 
      {isPending && <p>Loading...</p>}
      {isError && error && (
        <p style={{ color: "red" }}>Error: {error.message}</p>
      )}
 
      {isSuccess && data && (
        <ul>
          {data.map((user: User) => (
            <li key={user.id}>
              {user.name} - {user.email}
            </li>
          ))}
        </ul>
      )}
 
      <button onClick={refetch} disabled={isPending}>
        {isPending ? "Fetching..." : "Refetch Data"}
      </button>
    </div>
  );
}

API

useFetch

useFetch.ts
function useFetch<T, E = string>(
  url: string,
  reqOpt?: RequestInit,
): UseFetchResult<T, E>;

Fetches data from the provided URL using the specified request options.

This function uses fetch with an AbortController to allow for request cancellation if needed. Updates the state with the response data, error, or loading status based on the fetch result.

Parameters

NameTypeDescription
urlstringThe URL of the API endpoint.
reqOpt?RequestInitOptional configuration for the fetch request (e.g., method, headers).
TTType of the data returned by the API.
EEType of the error returned by the API (default is string).

Returns

NameTypeDescription
dataTThe data returned by the API, or null if no data has been received yet.
errorEThe error returned by the API, or null if no error has occurred.
isPendingbooleanA boolean indicating whether the fetch request is currently in progress.
isSuccessbooleanA boolean indicating if the fetch request was successful.
isErrorbooleanA boolean indicating if the fetch request resulted in an error.
refetch() => voidA function to manually trigger the fetch request again.

On this page