https://github.com/vladagurets/react-cancelable
⚜️ Make cancelable requests with react-hooks
https://github.com/vladagurets/react-cancelable
cancelable react request
Last synced: 12 months ago
JSON representation
⚜️ Make cancelable requests with react-hooks
- Host: GitHub
- URL: https://github.com/vladagurets/react-cancelable
- Owner: vladagurets
- License: mit
- Archived: true
- Created: 2022-02-12T16:34:30.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2023-02-15T21:01:29.000Z (over 3 years ago)
- Last Synced: 2024-07-11T14:46:22.577Z (almost 2 years ago)
- Topics: cancelable, react, request
- Language: TypeScript
- Homepage: https://vladagurets.github.io/react-cancelable/
- Size: 867 KB
- Stars: 62
- Watchers: 2
- Forks: 0
- Open Issues: 3
-
Metadata Files:
- Readme: readme.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://www.supportukraine.co/)
react-cancelable
Internet traffic economizer
[![version][npm-version-badge]][npm-url]
[![downloads][weekly-downloads-badge]][npm-url]
[npm-url]: https://www.npmjs.com/package/react-cancelable
[npm-version-badge]: https://badge.fury.io/js/react-cancelable.svg
[total-downloads-badge]: https://img.shields.io/npm/dt/react-cancelable.svg
[weekly-downloads-badge]: https://img.shields.io/npm/dm/react-cancelable.svg
# Table of Contents
1. [Motivation](#motivation)
2. [Instalation](#instalation)
3. [Tools](#tools)
1. [useCancelableReq](#usecancelablereq)
2. [useCancelableImg](#usecancelableimg)
3. [cancelable HOF](#cancelable-hof)
4. [Fetch vs Axios](#fetch-vs-axios)
5. [Best practices (WIP)](#best-practices)
# Motivation
In most of cases client consumes a lot of excess internet traffic. Modern web applications make a huge bunch of requests per conventional time unit then a lot of clients don't wait until all requests made by web app are finished. As a result, the browser expects data that will no longer be used.
With react-cancelable you can easily cancel requests at any step of the [request's lifecycle](https://dev.to/dangolant/things-i-brushed-up-on-this-week-the-http-request-lifecycle-) and consume fewer traffic bytes.
# Instalation
```
npm install react-cancelable
```
```
yarn add react-cancelable
```
Before installation be sure you have installed the required peer dependencies to your project
```json
{
"react": "^17.0.0",
}
```
# Tools
## useCancelableReq
Make cancelable request. Hook helps you to control request canceling by React Component Lifecycle or by your own.
### Signature
```typescript
type RequestFn = (controller: AbortController) => Promise
type Opts = {
isLazy?: boolean;
cancelOnUnmount?: boolean;
controller?: AbortController;
onComplete?: (res: any) => void;
onFail?: (error: any) => void
onCancel?: VoidFunction;
}
type Artefacts = {
res?: Response;
data?: any;
error?: any;
isLoading: boolean;
cancel: VoidFunction,
makeLazyRequest: VoidFunction | null;
}
useCancelableReq(fn: RequestFn, opts?: Opts): Artefacts
```
### API
Name
Description
Default
isLazy
Control request by your own if true. By default, a request will be made on the component mount
false
cancelOnUnmount
Request will be canceled on component unmount if true
true
controller
By default component will create instance automaticaly under the hood. If yoo want to controll multiple requests with one conteroller pass your own instance of AbortControler
undefined
onComplete
Trigger after request is completed
undefined
onFail
Trigger after request is failed
undefined
onCancel
Trigger after request is canceled
undefined
res
Response object
undefined
data
Payload of a request
undefined
error
Error of a request
undefined
isLoading
Flag to determine active status of request. If isLazy is true isLoading is false by default
true
cancel
Request cancel trigger
function
makeLazyRequest
Make request trigger. If isLazy is true makeLazyRequest is function
null
### Example
```jsx
import React from 'react'
import { useCancelableReq } from 'react-cancelable'
function makeRequest(controller) {
// Pass signal to your request
return fetch("YOUR_ENDPOINT", { signal: controller.signal })
}
function Item() {
const { data, isLoading, error } = useCancelableReq(makeRequest)
return (
<>
{isLoading && Loading...}
{error && Error occured}
{data && Data is fetched}
>
)
}
```
## useCancelableImg
Make cancelable request. Hook helps you to cancel requested image.
### Signature
```typescript
type RequestFn = (controller: AbortController) => Promise
type Opts = {
isLazy?: boolean;
cancelOnUnmount?: boolean;
controller?: AbortController;
onComplete?: (res: any) => void;
onFail?: (error: any) => void
onCancel?: VoidFunction;
}
type Artefacts = {
res?: Response;
src?: string;
error?: any;
isLoading: boolean;
cancel: VoidFunction,
makeLazyRequest: VoidFunction | null;
}
useCancelableImg(fn: RequestFn, opts?: Opts): Artefacts
```
### API
Name
Description
Default
isLazy
Control request by your own if true. By default, a request will be made on the component mount
false
cancelOnUnmount
Request will be canceled on component unmount if true
true
controller
By default component will create instance automaticaly under the hood. If yoo want to controll multiple requests with one conteroller pass your own instance of AbortControler
undefined
onComplete
Trigger after request is completed
undefined
onFail
Trigger after request is failed
undefined
onCancel
Trigger after request is canceled
undefined
res
Response object
undefined
src
Generated ObjectURI to Blob image after request done
undefined
error
Error of a request
undefined
isLoading
Flag to determine active status of request. If isLazy is true isLoading is false by default
true
cancel
Request cancel trigger
function
makeLazyRequest
Make request trigger. If isLazy is true makeLazyRequest is function
null
### Example
```jsx
import React from 'react'
import { useCancelableReq } from 'react-cancelable'
function getImage(controller) {
// Pass signal to your request
return fetch('IMAGE_URL', { signal: controller.signal })
}
function Item() {
const { src, isLoading, error } = useCancelableImg(getImage)
return (
<>
{isLoading && Loading...}
{src &&
}
>
)
}
```
## cancelable HOF
Hight order function to create cancelable requests
### Signature
```typescript
type RequestFn = (controller: AbortController) => Promise
type RequestPromise = Promise & { cancel: VoidFunction }
cancelable(fn: RequestFn, controller?: AbortController): RequestPromise
```
### API
Name
Description
Default
fn
Callback that returns Promise generated by HTTP client
function
controller
By default component will create instance automaticaly under the hood. If yoo want to controll multiple requests with one conteroller pass your own instance of AbortControler
undefined
cancel
Request cancel trigger. Property added to returned Promise
function
### Example
```javascript
import { cancelable } from 'react-cancelable'
function makeRequest(controller) {
return fetch("YOUR_ENDPOINT", { signal: controller.signal })
}
// Wrap your request
const request = cancelable(makeRequest)
setTimeout(() => {
// Cancel request later
request.cancel()
}, 1000)
```
# Fetch vs Axios
There is no difference what HTTP client you use. Package have one important rule - HTTP client must accept [AbortController signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/signal).
```javascript
function makeFetchRequest(controller) {
return fetch("YOUR_ENDPOINT", { signal: controller.signal })
}
function makeAxiosRequest(controller) {
return axios.get("YOUR_ENDPOINT", { signal: controller.signal })
}
```
# Best practices (WIP)
Cancel multiple similar request via one AbortController. Each helper can take ```controller``` parameter.
```javascript
import { cancelable } from 'react-cancelable'
const controller = new AbortController()
function makeRequest(controller) {
return fetch("YOUR_ENDPOINT", { signal: controller.signal })
}
// Make requests
new Array(100).fill(0).forEach(() => { cancelable(makeRequest, controller) } )
setTimeout(() => {
// Stop all pending requests
controller.abort()
}, 1000)
```