Skip to content

Commit

Permalink
doc: write documentation for useFetch hook (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
alamenai authored Jun 2, 2024
1 parent 332a5be commit 3dbd771
Show file tree
Hide file tree
Showing 3 changed files with 132 additions and 4 deletions.
6 changes: 3 additions & 3 deletions pages/hooks/_meta.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"use-abort-controller": "useAbortController",
"use-fetch": "useFetch",
"use-history": "useHistory",
"use-local-storage": "useLocalStorage",
"use-persistent-state":"usePersistentState",
"use-persistent-state": "usePersistentState",
"use-query-params": "useQueryParams",
"use-timeout":"useTimeout"

"use-timeout": "useTimeout"
}
124 changes: 124 additions & 0 deletions pages/hooks/use-fetch.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# useFetch

<h3 className="mt-4 text-xl font-normal text-gray-400">A custom hook for fetching data from an API.</h3>

## Add hook

Create a file `use-fetch.ts` and copy & paste the code from [useFetch](/hooks/use-fetch#hook).

## Usage

```tsx

import React, { useEffect, useState } from 'react';
import { useFetch } from './useFetch';

type Product = {
id: string
title: string
}

function App() {
const { data, isLoading, error, refetch } = useFetch<Product[]>('https://fakestoreapi.com/products');

if (isLoading) {
return <div>Loading...</div>;
}

if (error) {
return <div>Error: {error.message}</div>;
}

return (
<div>
<h1>useFetch Example</h1>
<p>Data: {JSON.stringify(data)}</p>
<button onClick={refetch}>Refetch Data</button>
</div>
);
}

export default App;

```

### Hook

```ts copy
import { useEffect, useState } from 'react'

export const useFetch = <DataType>(url: string, trigger = true, requestOptions?: RequestInit) => {
const [error, setError] = useState<Error | undefined>(undefined)

const [data, setData] = useState<DataType | undefined>(undefined)

const [isLoading, setIsLoading] = useState(!trigger || false)

const [isTriggered, setIsTriggered] = useState(trigger)

const startTrigger = () => setIsTriggered(true)

const fetchData = async () => {
try {
setIsLoading(true)

const response = await fetch(url, requestOptions)

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}

const result = await response.json()

setData(result)

setError(undefined)
} catch (error) {
if (error instanceof Error) {
setError(error)
}
} finally {
setIsLoading(false)
}
}

useEffect(() => {
setIsTriggered(trigger)
}, [trigger])

useEffect(() => {
if (isTriggered) {
fetchData()
}
}, [isTriggered])

return { data, isLoading, error, refetch: fetchData, trigger: startTrigger }
}

```

## API

[`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)

A custom hook for fetching data from a URL.

<h1 className='text-xl font-medium mt-6'>Parameters</h1>

| Parameter | Type | Description |
| ---- | ---- | ----------- |
| `url` | `string` | The URL from which to fetch the data. |
| `trigger` | `boolean` (optional) | If `true`, the fetch operation will be triggered immediately. Default is `true`. |
| `requestOptions` | `RequestInit` (optional) | Options to pass to the `fetch` function. |

<h1 className='text-xl font-medium mt-6'>Returns</h1>

An object containing the following properties:

| Name | Type | Description |
| ---- | ---- | ----------- |
| `data` | `DataType \| undefined` | The fetched data, if available. |
| `isLoading` | `boolean` | Indicates whether the fetch operation is in progress. |
| `error` | `Error \| undefined` | An error object, if an error occurred during the fetch operation. |
| `refetch` | `() => Promise<void>` | A function to manually trigger the fetch operation. |
| `trigger` | `() => void` | A function to manually trigger the fetch operation. |
6 changes: 5 additions & 1 deletion theme.config.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,14 @@ const config = {
},
sidebar: {
titleComponent({ title, type }) {
const newHooks = ["useTimeout", "usePersistent", "useFetch"];

return (
<div className="flex items-center justify-between relative w-full">
<div>{title}</div>
{(title === "useTimeout" || title === "usePersistentState") && (
{(title === "useTimeout" ||
title === "usePersistentState" ||
title === "useFetch") && (
<Badge className=" absolute -right-[0.5em] bg-transparent border-lime-400 text-lime-500 px-[0.5em]">
New
</Badge>
Expand Down

0 comments on commit 3dbd771

Please sign in to comment.