# use-fetch-url

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

Latest version **0.1.42** (published 2023-02-03) · ISC license · 0 weekly downloads

## Install

```sh
npm install use-fetch-url
pnpm add use-fetch-url
yarn add use-fetch-url
bun add use-fetch-url
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.1.42 |
| Published | 2023-02-03 |
| First published | 2023-02-02 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 9.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Maintainers | britanskii |
| Keywords | TypeScript, Enum, Fetch API, Data Fetching, Error Handling, Type Aliases |

## Links

- npm: https://www.npmjs.com/package/use-fetch-url
- npm.io page: https://npm.io/package/use-fetch-url

## Alternatives

- [@openai/codex-sdk](https://npm.io/package/@openai/codex-sdk.md) — 731.4K weekly downloads
- [babel-plugin-transform-react-jsx](https://npm.io/package/babel-plugin-transform-react-jsx.md) — 565.0K weekly downloads
- [babel-helper-remove-or-void](https://npm.io/package/babel-helper-remove-or-void.md) — 508.5K weekly downloads
- [@pnpm/store-controller-types](https://npm.io/package/@pnpm/store-controller-types.md) — 186.9K weekly downloads
- [react-native-signature-canvas](https://npm.io/package/react-native-signature-canvas.md) — 155.6K weekly downloads

## Recent versions

- 0.1.42 (latest) — 2023-02-03
- 0.1.41 — 2023-02-03
- 0.1.40 — 2023-02-03
- 0.1.39 — 2023-02-03
- 0.1.38 — 2023-02-02
- 0.1.37 — 2023-02-02
- 0.1.36 — 2023-02-02
- 0.1.35 — 2023-02-02
- 0.1.34 — 2023-02-02
- 0.1.33 — 2023-02-02
- 0.1.32 — 2023-02-02
- 0.1.31 — 2023-02-02
- 0.1.30 — 2023-02-02
- 0.1.29 — 2023-02-02
- 0.1.28 — 2023-02-02
- … 28 more at https://npm.io/package/use-fetch-url/versions

## 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
```typescript
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:

```typescript
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
```typescript
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:

```typescript
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.

```typescript
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:<br>- `status` of `FetchStatus.COMPLETE`<br>- `data` of type `T`<br>- `error` of `null`. |
| `LoadingFetch`        | Represents a fetch operation in progress with:<br>- `status` of `FetchStatus.LOADING`<br>- `data` of `null`<br>- `error` of `null`. |
| `ErrorFetch<K>`       | Represents a failed fetch operation with:<br>- `status` of `FetchStatus.ERROR`<br>- `data` of `null`<br>- `K` as the type of error. |
| `AnswerFetch<T, K>`  | Represents any of the three fetch states, with:<br>- `T` as the type of successful data<br>- `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.
```typescript
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.

```typescript
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>
  );
};
```

---
_Source: https://npm.io/package/use-fetch-url · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
