Function useFetch

  • Fetches the provided URL and optionally parses the response. Aborts requests when a new request is started before the previous has finished to prevent flickering of stale responses by default.

    Type Parameters

    • T = any

      Type of the returned result. This is only for convenience when using TypeScript. You can put the type here you expect to receive depending on the selected parseType. This allows you to avoid making manual type assertions on the returned data. Here's a list of what parseTypes result in which return types:

      • "html": Document
      • "xml", "svg": XMLDocument
      • "text": string
      • "response": Response
      • "json" (default): any - When parsing JSON it is generally recommended to pass a custom type instead.

    Parameters

    • url: string

      The resource to fetch

    • options: FetchOptions<T> = {}

      Allows you to configure how useFetch makes and returns requests

    Returns FetchResult<T | undefined>

    FetchResult - An object containing information about the result of a fetch request

    const DemoUseFetch = () => {
    const [value, setValue] = useState("");
    const {loading, data} = useFetch<{
    data: { title: string }[]
    }>(
    "https://api.artic.edu/api/v1/artworks/search?q=" + encodeURIComponent(value)
    );
    const list = data?.data.map((e, i) => <li key={i}>{e.title}</li>)
    return (
    <div>
    <input
    type="text"
    value={value}
    onInput={(e) => setValue((e.target as HTMLInputElement).value)}
    />
    <ul>
    {loading ? "LOADING..." : list}
    </ul>
    </div>
    );
    };