npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-fetch-url

v0.1.42

Published

A custom hooks in TypeScript for fetching data from a URL and managing its state, including status and error information.

Downloads

46

Readme

useFetchUrl

A custom hooks in TypeScript for fetching data from a URL and managing its state, including status and error information.

API Reference

useFetchUrl Hook in Typescript

Hook that makes the request itself

Parameters

useFetchUrl<T, K = unknown>(url: string, initialValue: T) => AnswerInterface<T, K>

| Parameters | Type | Description | | :-------- | :------- | :-------------------------------- | | url | string | Required. URL to fetch data from | | initialValue | T | Initial value of data (optional with default null) | | T | any type | Type of data | | K | unknown or any type | Type of error (optional with default unknown) |

Usage

Call the hook useFetchUrl with two generic parameters, T and K, representing the type of data to be fetched and the type of error, respectively. The second generic parameter is optional and has a default of unknown.

Pass in two arguments: the URL to fetch data from and an initial value for the data (optional with default null).

Example:

import { useFetchUrl } from "./useFetchUrl";
import { FetchStatus } from "./FetchStatus";

interface IData {
  message: string;
}

interface IError {
  message: string
}

const initialValue: IData = { message: "Important things!" };

const App = () => {
  const { data, status, error } = useFetchUrl<IData, IError>("https://your-url", initialValue);

  if (status === FetchStatus.LOADING) {
    return <div>Loading...</div>;
  }

  if (status === FetchStatus.ERROR) {
    return <div>{error}</div>;
  }

  return <div>{data.message}</div>;
};

Return type

The hook returns an object with three properties:

  • data: state of data of type T
  • status: status of fetch operation of type FetchStatus
  • error: error message of type K (if any)

useFetch Hook in TypeScript

Hook using a passed promise

Parameters

useFetch<T, K = unknown>(PromiseFunction: () => Promise<T>, initialValue: T) => AnswerInterface<T, K>

| Parameters | Type | Description | | :-------- | :------- | :-------------------------------- | | PromiseFunction | () => Promise<T> | Required. Promise function to fetch data from | | initialValue | T | Initial value of data (optional with default null) | | T | any type | Type of data | | K | unknown or any type | Type of error (optional with default unknown) |

Usage

Call the hook useFetch with two generic parameters, T and K, representing the type of data to be fetched and the type of error, respectively. The second generic parameter is optional and has a default of unknown.

Pass in two arguments: the Promise function to fetch data from and an initial value for the data (optional with default null).

Example:

import { useFetch } from "./useFetch";
import { FetchStatus } from "./FetchStatus";

interface IData {
  message: string;
}

interface IError {
  message: string
}

const initialValue: IData = { message: "" };

const fetchData = () => {
  return new Promise<Data>(resolve => {
    setTimeout(() => {
      resolve({ message: "Important things!" });
    }, 1000);
  });
};

const App = () => {
  const { data, status, error } = useFetch<IData, string>(fetchData, initialValue);

  if (status === FetchStatus.LOADING) {
    return <div>Loading...</div>;
  }

  if (status === FetchStatus.ERROR) {
    return <div>{error}</div>;
  }

  return <div>{data.message}</div>;
};

Return type

The hook returns an object with three properties:

  • data: state of data of type T
  • status: status of fetch operation of type FetchStatus
  • error: error message of type K (if any)

FetchStatus Enum

This is a TypeScript enum that consists of three fields: COMPLETE, LOADING, and ERROR. It represents the status of a fetch operation.

enum FetchStatus {
  COMPLETE,
  LOADING,
  ERROR
}

AnswerFetch Type

A type in TypeScript that describes the possible states of a fetch operation, including complete, loading, and error states.

Usage

This type is used to describe the shape of an object returned from a fetch operation, with three possible states: CompleteFetch, LoadingFetch, and ErrorFetch.

Types

| Type | Description | |-----------------------|----------------------------------------------------------------------------------------| | CompleteFetch<T> | Represents a successful fetch operation with data of type T. Includes:- status of FetchStatus.COMPLETE- data of type T- error of null. | | LoadingFetch | Represents a fetch operation in progress with:- status of FetchStatus.LOADING- data of null- error of null. | | ErrorFetch<K> | Represents a failed fetch operation with:- status of FetchStatus.ERROR- data of null- K as the type of error. | | AnswerFetch<T, K> | Represents any of the three fetch states, with:- T as the type of successful data- K as the type of error. |

Advanced usage

You can create a wrapper for the hook to useFetchUrl even more cleanly.

This is the useUsers file.

interface IUser {
    name: string,
    age: number
}

//You can do the same using the useFetch hook
export const useUsers = () => useFetchUrl<IUser[]>("https://your-url/users")

This is the Users file.

import { useUsers } from "./hooks/useUsers";

const Users = () => {
  const { data, status, error } = useUsers();
  const {COMPLETE, ERROR, LOADING} = FetchStatus

  if (status === LOADING) 
    return <div>Loading...</div>;
  if (status === ERROR) 
    return <div>{error}</div>;
  if (status === COMPLETE)
  return (
      <div>
        {data.map(user => 
            <div>
                {user.name} - {user.age}
            </div>
        )}
      </div>
  );
};