useDelete
Introduction
The useDelete
hook is a custom React Hook that facilitates DELETE requests and handles the loading state and errors for such requests. It is particularly useful when you need to delete data from a server or API and want to handle the loading and error states in your React components efficiently.
Usage
import React from "react";
import { useDelete } from "@cannonui/reacthooks";
const DeleteComponent = () => {
const deleteUrl = "https://api.example.com/resource/1";
const { res, isLoading, err } = useDelete(deleteUrl, {
// Optional configuration options, if needed
});
if (isLoading) {
return <div>Loading...</div>;
}
if (err) {
return <div>Error: {err.message}</div>;
}
return <div>{res ? <div>Resource deleted successfully!</div> : null}</div>;
};
export default DeleteComponent;
// server mockup using express
app.delete("/resource/:id", (req, res) => {
res.status(200).send("delete response");
});
Return Value
The hook returns an object containing the following properties:
Name | Type | Description |
---|---|---|
res | ResponseData | null | The response data from the DELETE request, if any. |
isLoading | boolean | A boolean indicating whether the request is loading. |
err | Error | null | The error object in case of an error, if any. |
Parameters
Name | Type | Description |
---|---|---|
url | string | The URL to which the DELETE request will be sent. |
config | ExtendedRequestOptions (optional) | Additional configuration for the DELETE request. |
Extended Request Options
The config
parameter of the useGet
hook allows you to customize the behavior of the GET request using the following properties:
Name | Type | Description |
---|---|---|
debounce (optional) | number | The time in milliseconds to wait before sending the request after the last trigger. Defaults to undefined . |
polling (not available yet) | number | The interval in milliseconds between periodic GET requests. Allows periodic polling for updated data. Defaults to undefined . |
tabular | TabularFormat (optional) | An optional object specifying the format of tabular data if your API returns data in a tabular format. |
params (optional) | Record<string, string | number> | Additional parameters to be sent along with the GET request. Used for pagination or filtering. |
data (optional) | any | Data to be sent as the request body. Useful for sending data in POST requests. Defaults to undefined . |
files (optional) | File[] (optional) | An array of File objects representing files to be uploaded in a file upload request. |
isFormData (optional) | boolean | A flag indicating whether the request body is of type FormData. Defaults to false . |
timeout (optional) | number | The timeout duration in milliseconds for the GET request. If the request takes longer, it will be aborted. Defaults to undefined . |
offline (not available yet) | boolean (optional) | A flag to indicate whether to store and serve the request from cache when the device is offline. Defaults to false . |
onDataChunk (optional) | (chunk: ReadableStreamReadResult<any>) | A function to process chunks of data as they arrive when using streaming responses. Defaults to undefined . |
onBefore (optional) | Array<(params: ExtendedRequestOptions) => any> | An array of functions to be executed before sending the GET request. Defaults to an empty array. |
onSuccess (optional) | Array<(data: any, params: ExtendedRequestOptions) => any> | An array of functions to be executed when the GET request is successful. Defaults to an empty array. |
onError (optional) | (error: Error) | A function to be executed when an error occurs during the GET request. Defaults to undefined . |
onFinally (optional) | (params: ExtendedRequestOptions, data: any, error: any) => void | A function to be executed after the GET request is completed, regardless of success or error. Defaults to undefined . |
maxRetry (optional) | number (optional) | The maximum number of times to retry the GET request in case of network errors. Defaults to undefined . |
body (optional) | BodyInit | null | The request body to be sent with the GET request. Can be null . |
cache (optional) | RequestCache | A string indicating how the request will interact with the browser’s cache to set request’s cache. |
credentials (optional) | RequestCredentials | A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request’s credentials. |
headers (optional) | HeadersInit | A Headers object, an object literal, or an array of two-item arrays to set request’s headers. |
integrity (optional) | string | A cryptographic hash of the resource to be fetched by request. Sets request’s integrity. |
keepalive (optional) | boolean | A boolean to set request’s keepalive. |
method (optional) | string | A string to set request’s method. |
mode (optional) | RequestMode | A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request’s mode. |
redirect (optional) | RequestRedirect | A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request’s redirect. |
referrer (optional) | string | A string whose value is a same-origin URL, “about”, or the empty string, to set request’s referrer. |
referrerPolicy (optional) | ReferrerPolicy | A referrer policy to set request’s referrerPolicy. |
signal (optional) | AbortSignal | null | An AbortSignal to set request’s signal. |
window (optional) | null | Can only be null. Used to disassociate request from any Window. |
Features
- Facilitates DELETE requests in React components, simplifying the process of deleting data from a server or API.
- Automatically handles the loading state, allowing you to display a loading indicator while the DELETE request is ongoing.
- Provides an error object to handle and display any errors that occur during the DELETE request.
- Can be customized using the optional
config
parameter to add additional headers, set a timeout, or handle request retries.
Example
-
In the
DeleteComponent
, we define thedeleteUrl
, which is the URL of the resource we want to delete. Replace"https://api.example.com/resource/1"
with the actual endpoint URL of the resource you want to delete. -
We call the
useDelete
hook with thedeleteUrl
and an optional configuration object. TheuseDelete
hook handles the DELETE request to the specified URL, and it returns an object with three properties:res
,isLoading
, anderr
. -
res
contains the response data from the DELETE request, if any. If the request is successful, it may contain information about the deleted resource. If the request fails or no data is returned, it will benull
. -
isLoading
is a boolean that indicates whether the DELETE request is still loading. While the request is ongoing,isLoading
will betrue
, allowing you to display a loading indicator or perform other actions. -
err
is an error object that contains information about any errors that occur during the DELETE request. If there are no errors, it will benull
. If an error occurs, you can display an error message to the user. -
The
DeleteComponent
component then conditionally renders different content based on the state of the DELETE request. If the request is still loading, it displays “Loading…“. If there’s an error, it displays an error message with the error’smessage
. If the request is successful (res
is notnull
), it displays a success message stating that the resource was deleted successfully.
You can use the DeleteComponent
in your application whenever you need to handle DELETE requests to delete resources from the server, and it will automatically manage the loading and error states, providing a smooth user experience.
Use Scenario
The useDelete
hook is useful in scenarios where you need to perform DELETE requests in a React component and handle the loading and error states associated with those requests. It allows you to interact with APIs or servers to delete resources while maintaining a smooth user experience by displaying loading indicators and handling errors gracefully.