useAsyncEffect
In general, the callback function passed to useEffect cannot be an async function.
useAsyncEffect is a custom hook for using async functions with useEffect.
Code
Interface
typescript
function useAsyncEffect(effectCallback: () => Promise<void>, deps?: DependencyList): void
Parameters
| Name | Type | Description |
|---|---|---|
effectCallback | () => Promise<void> | The async function to execute |
deps | DependencyList | Dependency array that re-runs the effect when changed |
Usage
typescript
import { useAsyncEffect, DebounceHandler } from '@modern-kit/react'
const Example = () => {
const [data, setData] = useState(null)
const [id, setId] = useState(1);
const fetchData = async () => {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
const data = await res.json()
setData(data)
}
useAsyncEffect(fetchData, [id]);
return (
<div>
{/* Use DebounceHandler to debounce the button click event. */}
<DebounceHandler wait={500} capture={'onClick'}>
<button onClick={() => setId(id + 1)}>ID Change: {id}</button>
</DebounceHandler>
<p>ID: {data?.id}</p>
<p>TITLE: {data?.title}</p>
<p>BODY: {data?.body}</p>
</div>
);
}
Example
ID:
TITLE:
BODY: