Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-cancelable

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-cancelable

Make cancelable requests with react-hooks

  • 1.0.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2
Maintainers
1
Weekly downloads
 
Created
Source

react-cancelable

Internet traffic economizer


version downloads


Table of Contents

  1. Motivation
  2. Instalation
  3. Tools
    1. useCancelableReq
    2. useCancelableImg
    3. cancelable HOF
  4. Fetch vs Axios
  5. Best practices (WIP)

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

But don't worry you can easily deal with it with the latest AbortController API and react-cancelable


Instalation

npm install react-cancelable
yarn add react-cancelable

Before installation be sure you have installed the required peer dependencies to your project


{
  "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


type RequestFn = (controller: AbortController) => Promise<any>

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


NameDescriptionDefault
isLazyControl request by your own if true. By default, a request will be made on the component mountfalse
cancelOnUnmountRequest will be canceled on component unmount if truetrue
controllerBy default component will create instance automaticaly under the hood. If yoo want to controll multiple requests with one conteroller pass your own instance of AbortControlerundefined
onCompleteTrigger after request is completedundefined
onFailTrigger after request is failedundefined
onCancelTrigger after request is canceledundefined
resResponse objectundefined
dataPayload of a requestundefined
errorError of a requestundefined
isLoadingFlag to determine active status of request. If isLazy is true isLoading is false by defaulttrue
cancelRequest cancel triggerfunction
makeLazyRequestMake request trigger. If isLazy is true makeLazyRequest is functionnull

Example


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 && <span>Loading...</span>}
      {error && <span>Error occured</span>}
      {data && <span>Data is fetched</span>}
    </>
  )
}

useCancelableImg


Make cancelable request. Hook helps you to cancel requested image.


Signature


type RequestFn = (controller: AbortController) => Promise<any>

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


NameDescriptionDefault
isLazyControl request by your own if true. By default, a request will be made on the component mountfalse
cancelOnUnmountRequest will be canceled on component unmount if truetrue
controllerBy default component will create instance automaticaly under the hood. If yoo want to controll multiple requests with one conteroller pass your own instance of AbortControlerundefined
onCompleteTrigger after request is completedundefined
onFailTrigger after request is failedundefined
onCancelTrigger after request is canceledundefined
resResponse objectundefined
srcGenerated ObjectURI to Blob image after request doneundefined
errorError of a requestundefined
isLoadingFlag to determine active status of request. If isLazy is true isLoading is false by defaulttrue
cancelRequest cancel triggerfunction
makeLazyRequestMake request trigger. If isLazy is true makeLazyRequest is functionnull

Example


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 && <span>Loading...</span>}
      {src && <img src={src} />}
    </>
  )
}

cancelable HOF


Hight order function to create cancelable requests


Signature


type RequestFn = (controller: AbortController) => Promise<any>

type RequestPromise = Promise<any> & { cancel: VoidFunction }

cancelable(fn: RequestFn, controller?: AbortController): RequestPromise

API


NameDescriptionDefault
fnCallback that returns Promise generated by HTTP clientfunction
controllerBy default component will create instance automaticaly under the hood. If yoo want to controll multiple requests with one conteroller pass your own instance of AbortControlerundefined
cancelRequest cancel trigger. Property added to returned Promisefunction

Example


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.

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.

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)

Keywords

FAQs

Package last updated on 06 Apr 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc