useFetch
Get data with built-in load and error statuses.
Características
-
GETrequests are initiated as soon as the component is mounted, unless you setimmediatetofalse. -
Supports standard
fetchAPI options, such as customizing request headers, method, body, and more. -
Automatic serialization of the request body to JSON (
application/json), using thedataoption.
Installation
Install the custom hook from your terminal.
npm i @raddix/use-fetch
Usage
Get the data
You can get data from an API by simply providing a URL.
Avoiding an immediate request
To prevent the request from being triggered as soon as the component is mounted, add immediate: false to
the options object of the useFetch hook.
This will prevent the request from being triggered until the execute function is called.
Sending JSON data
To send a POST request with JSON-encoded data, use the data option instead of the body
option of the options object passed to the useFetch hook.
Abort a request
useFetch automatically cancels any unfinished requests before calling another one.
If you want to cancel a request after a 4 second timeout you can do so using the
abort function.
API
Parameters
| Name | Description | Required | Type |
|---|---|---|---|
| url | La URL de la api o servidor | Si | string |
| options | Additional options for the fetch request, such as headers or request methods. | No | object |
Configurable options
| Name | Description | Required | Type |
|---|---|---|---|
| immediate | Start a request as soon as the component is mounted. | No | boolean |
| data | Accepts object type data that is passed serialized to the body. | No | boolean |