use-fetch-url
Version:
A custom hooks in TypeScript for fetching data from a URL and managing its state, including status and error information.
206 lines (147 loc) • 6.04 kB
Markdown
# 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>
);
};
```