|
| 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. | |
0 commit comments