useFetch
Fetch data with a URL and search parameters using useAsync hook.
Options
Name | Type | Description |
---|---|---|
url | String or URL | the fetch URL. |
params | Object | URL search params. |
fetchOnMount | Boolean | start fetching when the component is mounted. |
...init | Object | request init options. |
Return Values
Name | Type | Description |
---|---|---|
data | Any | resolved data from the function. |
isPending | Boolean | the loading state. |
response | Object | Response object from the fetch function. |
callback | Fnuction | the fatch callback function. |
abort | Fnuction | cancel the fetch request using an AbortController. |
error | Unknown | cached error if it exists. |
Example Usage
tsx
import { useFetch } from 'react-pre-hooks';
type Data = {
users: {
id: number;
firstName: string;
lastName: string;
image: string;
email: string;
}[];
};
export default function Users() {
const { data, isPending, callback, error } = useFetch<Data>({
url: 'https://dummyjson.com/users',
params: { limit: 12 },
fetchOnMount: true
});
return (
<main>
<button onClick={callback}>Refetch</button>
{isPending ? (
<p>Loading...</p>
) : error ? (
<p>Something went wrong!</p>
) : (
<ul>
{data?.users.map(user => (
<li key={user.id}>
<img src={user.image} alt={user.firstName} />
<p>{user.firstName + ' ' + user.lastName}</p>
<p>{user.email}</p>
</li>
))}
</ul>
)}
</main>
);
}
import { useFetch } from 'react-pre-hooks';
type Data = {
users: {
id: number;
firstName: string;
lastName: string;
image: string;
email: string;
}[];
};
export default function Users() {
const { data, isPending, callback, error } = useFetch<Data>({
url: 'https://dummyjson.com/users',
params: { limit: 12 },
fetchOnMount: true
});
return (
<main>
<button onClick={callback}>Refetch</button>
{isPending ? (
<p>Loading...</p>
) : error ? (
<p>Something went wrong!</p>
) : (
<ul>
{data?.users.map(user => (
<li key={user.id}>
<img src={user.image} alt={user.firstName} />
<p>{user.firstName + ' ' + user.lastName}</p>
<p>{user.email}</p>
</li>
))}
</ul>
)}
</main>
);
}