Skip to content

Commit 3dbd771

Browse files
authored
doc: write documentation for useFetch hook (#10)
1 parent 332a5be commit 3dbd771

File tree

3 files changed

+132
-4
lines changed

3 files changed

+132
-4
lines changed

pages/hooks/_meta.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
{
22
"use-abort-controller": "useAbortController",
3+
"use-fetch": "useFetch",
34
"use-history": "useHistory",
45
"use-local-storage": "useLocalStorage",
5-
"use-persistent-state":"usePersistentState",
6+
"use-persistent-state": "usePersistentState",
67
"use-query-params": "useQueryParams",
7-
"use-timeout":"useTimeout"
8-
8+
"use-timeout": "useTimeout"
99
}

pages/hooks/use-fetch.mdx

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# useFetch
2+
3+
<h3 className="mt-4 text-xl font-normal text-gray-400">A custom hook for fetching data from an API.</h3>
4+
5+
## Add hook
6+
7+
Create a file `use-fetch.ts` and copy & paste the code from [useFetch](/hooks/use-fetch#hook).
8+
9+
## Usage
10+
11+
```tsx
12+
13+
import React, { useEffect, useState } from 'react';
14+
import { useFetch } from './useFetch';
15+
16+
type Product = {
17+
id: string
18+
title: string
19+
}
20+
21+
function App() {
22+
const { data, isLoading, error, refetch } = useFetch<Product[]>('https://fakestoreapi.com/products');
23+
24+
if (isLoading) {
25+
return <div>Loading...</div>;
26+
}
27+
28+
if (error) {
29+
return <div>Error: {error.message}</div>;
30+
}
31+
32+
return (
33+
<div>
34+
<h1>useFetch Example</h1>
35+
<p>Data: {JSON.stringify(data)}</p>
36+
<button onClick={refetch}>Refetch Data</button>
37+
</div>
38+
);
39+
}
40+
41+
export default App;
42+
43+
```
44+
45+
### Hook
46+
47+
```ts copy
48+
import { useEffect, useState } from 'react'
49+
50+
export const useFetch = <DataType>(url: string, trigger = true, requestOptions?: RequestInit) => {
51+
const [error, setError] = useState<Error | undefined>(undefined)
52+
53+
const [data, setData] = useState<DataType | undefined>(undefined)
54+
55+
const [isLoading, setIsLoading] = useState(!trigger || false)
56+
57+
const [isTriggered, setIsTriggered] = useState(trigger)
58+
59+
const startTrigger = () => setIsTriggered(true)
60+
61+
const fetchData = async () => {
62+
try {
63+
setIsLoading(true)
64+
65+
const response = await fetch(url, requestOptions)
66+
67+
if (!response.ok) {
68+
throw new Error(`HTTP error! Status: ${response.status}`)
69+
}
70+
71+
const result = await response.json()
72+
73+
setData(result)
74+
75+
setError(undefined)
76+
} catch (error) {
77+
if (error instanceof Error) {
78+
setError(error)
79+
}
80+
} finally {
81+
setIsLoading(false)
82+
}
83+
}
84+
85+
useEffect(() => {
86+
setIsTriggered(trigger)
87+
}, [trigger])
88+
89+
useEffect(() => {
90+
if (isTriggered) {
91+
fetchData()
92+
}
93+
}, [isTriggered])
94+
95+
return { data, isLoading, error, refetch: fetchData, trigger: startTrigger }
96+
}
97+
98+
```
99+
100+
## API
101+
102+
[`useFetch<DataType>(url: string, trigger = true, requestOptions?: RequestInit): { data: DataType | undefined, isLoading: boolean, error: Error | undefined, refetch: () => Promise<void>, trigger: () => void }`](/hooks/use-fetch#hook)
103+
104+
A custom hook for fetching data from a URL.
105+
106+
<h1 className='text-xl font-medium mt-6'>Parameters</h1>
107+
108+
| Parameter | Type | Description |
109+
| ---- | ---- | ----------- |
110+
| `url` | `string` | The URL from which to fetch the data. |
111+
| `trigger` | `boolean` (optional) | If `true`, the fetch operation will be triggered immediately. Default is `true`. |
112+
| `requestOptions` | `RequestInit` (optional) | Options to pass to the `fetch` function. |
113+
114+
<h1 className='text-xl font-medium mt-6'>Returns</h1>
115+
116+
An object containing the following properties:
117+
118+
| Name | Type | Description |
119+
| ---- | ---- | ----------- |
120+
| `data` | `DataType \| undefined` | The fetched data, if available. |
121+
| `isLoading` | `boolean` | Indicates whether the fetch operation is in progress. |
122+
| `error` | `Error \| undefined` | An error object, if an error occurred during the fetch operation. |
123+
| `refetch` | `() => Promise<void>` | A function to manually trigger the fetch operation. |
124+
| `trigger` | `() => void` | A function to manually trigger the fetch operation. |

theme.config.jsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,14 @@ const config = {
5353
},
5454
sidebar: {
5555
titleComponent({ title, type }) {
56+
const newHooks = ["useTimeout", "usePersistent", "useFetch"];
57+
5658
return (
5759
<div className="flex items-center justify-between relative w-full">
5860
<div>{title}</div>
59-
{(title === "useTimeout" || title === "usePersistentState") && (
61+
{(title === "useTimeout" ||
62+
title === "usePersistentState" ||
63+
title === "useFetch") && (
6064
<Badge className=" absolute -right-[0.5em] bg-transparent border-lime-400 text-lime-500 px-[0.5em]">
6165
New
6266
</Badge>

0 commit comments

Comments
 (0)