API Reference
useFetch

useFetch

This hook allows you to easily fetch data from a given URL. It's a simple wrapper around the global fetch() function (opens in a new tab) and manages the fetching process, loading states, and potential errors.

Usage

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import useFetch into your component.

import { useFetch } from '@ridgehkr/useful'

Example

FetchPeople.tsx
import { useEffect } from 'react'
import { useFetch } from '@ridgehkr/useful'
 
function FetchPeople() {
  const { load, data, loading, error } = useFetch()
 
  // Load data when the component mounts
  useEffect(() => {
    load('https://swapi.dev/api/people/1')
  }, [])
 
  if (loading) {
    return <p>Loading...</p>
  }
 
  if (error) {
    return <p>Error: {error}</p>
  }
 
  return (
    <div>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  )
}

API Reference

Hook Signature

useFetch(converter?: ConverterFunction<T>): FetchState<T>

Parameters

converter?: ConverterFunction<T>
A function that takes the fetched data as an argument and returns a value of type T. The converter function is optional. If it is not provided, the fetched data will be returned as-is.

Return Value

The hook returns a FetchState object with the following properties:

PropertyTypeDescription
load(url: string, options?: object)A function that initiates the data fetching process from the specified URL. If provided, the options object is passed as the 2nd argument to the fetch() function (opens in a new tab).
dataT | undefinedThe fetched data. It will be undefined until the data is successfully fetched and processed
loadingbooleanA boolean indicating whether the data is currently being fetched
errorstring | nullAn error message that provides information about any fetch-related errors. It will be null if there are no errors.

A note on the load function

An additional options object can be provided to configure the fetch request. This will be directly passed into the fetch function. For more information, see the fetch documentation (opens in a new tab).