Skip to content

useFetch

Fetch data with a URL and search parameters using useAsync hook.

Options

NameTypeDescription
urlString or URLthe fetch URL.
paramsObjectURL search params.
fetchOnMountBooleanstart fetching when the component is mounted.
...initObjectrequest init options.

Return Values

NameTypeDescription
dataAnyresolved data from the function.
isPendingBooleanthe loading state.
responseObjectResponse object from the fetch function.
callbackFnuctionthe fatch callback function.
abortFnuctioncancel the fetch request using an AbortController.
errorUnknowncached error if it exists.

Example Usage

tsx
import { useFetch } from 'react-pre-hooks';

type Data = {
  users: {
    id: number;
    firstName: string;
    lastName: string;
    image: string;
    email: string;
  }[];
};

export default function Users() {
  const { data, isPending, callback, error } = useFetch<Data>({
    url: 'https://dummyjson.com/users',
    params: { limit: 12 },
    fetchOnMount: true
  });

  return (
    <main>
      <button onClick={callback}>Refetch</button>
      {isPending ? (
        <p>Loading...</p>
      ) : error ? (
        <p>Something went wrong!</p>
      ) : (
        <ul>
          {data?.users.map(user => (
            <li key={user.id}>
              <img src={user.image} alt={user.firstName} />
              <p>{user.firstName + ' ' + user.lastName}</p>
              <p>{user.email}</p>
            </li>
          ))}
        </ul>
      )}
    </main>
  );
}
import { useFetch } from 'react-pre-hooks';

type Data = {
  users: {
    id: number;
    firstName: string;
    lastName: string;
    image: string;
    email: string;
  }[];
};

export default function Users() {
  const { data, isPending, callback, error } = useFetch<Data>({
    url: 'https://dummyjson.com/users',
    params: { limit: 12 },
    fetchOnMount: true
  });

  return (
    <main>
      <button onClick={callback}>Refetch</button>
      {isPending ? (
        <p>Loading...</p>
      ) : error ? (
        <p>Something went wrong!</p>
      ) : (
        <ul>
          {data?.users.map(user => (
            <li key={user.id}>
              <img src={user.image} alt={user.firstName} />
              <p>{user.firstName + ' ' + user.lastName}</p>
              <p>{user.email}</p>
            </li>
          ))}
        </ul>
      )}
    </main>
  );
}

Released under the MIT License.