Skip to content

Repository files navigation

Logo

A library for canceling asynchronous requests that combines the Saborter library and React.

πŸ“š Documentation

The documentation is divided into several sections:

πŸ“¦ Installation

npm install saborter @saborter/react
# or
yarn add saborter @saborter/react

πŸ“– Possibilities

  • The aborter field always has the same reference to the Aborter instance.
  • Automatically abort the request when the component is unmounted.
  • Automatically unsubscribe from all listeners when the component is unmounted.

πŸš€ Quick Start

Basic Usage

import{useAborter}from'@saborter/react';constComponent=()=>{// Create an Aborter instance via the hookconst{ aborter }=useAborter();// Use for the requestconstfetchData=async()=>{try{constdata=awaitaborter.try((signal)=>fetch('/api/data',{ signal }));console.log('Data received:',data);}catch(error){console.error('Request error:',error);}};};

πŸ”§ API

useAborter

Props

const{ aborter }=useAborter(props?: UseAborterProps);

Props Parameters

ParameterTypeDescriptionRequired
propsUseAborterPropsAborter configuration optionsNo

UseAborterProps:

{/** Callback function for abort events. Associated with EventListener.onabort. It can be overridden via `aborter.listeners.onabort` */onAbort?: OnAbortCallback;/** A function called when the request state changes. It takes the new state as an argument. Can be overridden via `aborter.listeners.state.onstatechange` */
onStateChange?: OnStateChangeCallback;/** A flag responsible for releasing resources. This includes unsubscribing, clearing fields, and removing references to passed callback functions.@default true */
dispose?: boolean;}

Properties

aborter: Aborter

Returns the Aborter instance.

const{ aborter }=useAborter();// Using signal in the requestfetch('/api/data',{signal: aborter.signal});

requestState: RequestState

The current value of the request's state. May be undefined if the state has not yet been set.

The field is a react state associated with the aborter.listeners.state.value field.

Detailed documentation here

const{ requestState }=useAborter();console.log(requestState);// 'cancelled' / 'pending' / 'fulfilled' / 'rejected' / 'aborted'

useReusableAborter

Props

// The type can be found in `saborter/types`constreusableAborter=useReusableAborter(props?: ReusableAborterProps);

Props Parameters

ParameterTypeDescriptionRequired
propsReusableAborterPropsReusableAborter configuration optionsNo

ReusableAborterProps:

{/** * Determines which listeners are carried over when the abort signal is reset. * - If `true`, all listeners (both `onabort` and event listeners) are preserved. * - If `false`, no listeners are preserved. * - If an object, specific listener types can be enabled/disabled individually. */attractListeners?: boolean|AttractListeners;}

Properties

signal: AbortSignal

Returns the AbortSignal associated with the current controller.

constreusableAborter=useReusableAborter();// Using signal in the requestfetch('/api/data',{signal: reusableAborter.signal});

Methods

abort(reason?): void

Parameters:

  • reason?: any - the reason for aborting the request.

Immediately cancels the currently executing request.

Note

Can be called multiple times. Each call will restore the signal, and the aborted property will always be false.

🎯 Usage Examples

Basic Usage

import{useState}from'react';import{AbortError}from'saborter/errors';import{useAborter}from'@saborter/react';constComponent=()=>{// Create an Aborter instance via the hookconst{ aborter }=useAborter();const[user,setUser]=useState(null);const[loading,setLoading]=useState(false);// Use for the requestconstfetchData=async()=>{try{setLoading(true);constuser=awaitaborter.try((signal)=>fetch('/api/user',{ signal }));setUser(user);}catch(error){if(errorinstanceofAbortError){// An abort error will occur either when the `aborter.abort()` method is called// or when the component is unmounted.console.error('Abort error:',error);}console.error('Request error:',error);}finally{setLoading(false);}};return<h1>{loading ? 'Loading...' : user.fullname}</h1>;};

Using internal loading state

import{useState}from'react';import{AbortError}from'saborter/errors';import{useAborter}from'@saborter/react';constComponent=()=>{// Create an Aborter instance via the hookconst{ aborter, loading }=useAborter();const[user,setUser]=useState(null);// Use for the requestconstfetchData=async()=>{try{constuser=awaitaborter.try((signal)=>fetch('/api/user',{ signal }));setUser(user);}catch(error){if(errorinstanceofAbortError){// An abort error will occur either when the `aborter.abort()` method is called// or when the component is unmounted.console.error('Abort error:',error);}console.error('Request error:',error);}};return<h1>{loading ? 'Loading...' : user.fullname}</h1>;};

The AbortErrorinitiator changed while unmounting the component

import{AbortError}from'saborter/errors';import{useAborter}from'@saborter/react';constComponent=()=>{const{ aborter }=useAborter({onAbort: (error)=>{if(error.type==='aborted'&&error.initiator==='component-unmounted'){console.log('Component is unmounted!');}}});constfetchData=async()=>{constuser=awaitaborter.try((signal)=>fetch('/api/user',{ signal }));};};

Request interruption when unmounting a component with an external aborter

If you have an aborter instance that was created behind a component, for example, in a parent component, but you want to abort the request when the child is unmounted, you can use the useAbortWhenUnmount hook.

import{useAborter,useAbortWhenUnmount}from'@saborter/react';constChild=({ aborter })=>{useAbortWhenUnmount(aborter);return<div>Child component</div>;}constParent=()=>{const{ aborter }=useAborter();// Use for the requestconstfetchData=async()=>{try{constuser=awaitaborter.try((signal)=>fetch('/api/user',{ signal }));setUser(user);}catch(error){if(errorinstanceofAbortError&&error.initiator==='component-unmounted'){// handling request interruption due to component unmounting}}};return(<div>
Parent Component
<Childaborter={aborter}></div>
);
};

Using useReusableAborter

import{useEffect}from'react';import{useReusableAborter}from'@saborter/react';constComponent=()=>{constaborter=useReusableAborter();useEffect(()=>{// Attach listenersaborter.signal.addEventListener('abort',()=>console.log('Listener 1'));aborter.signal.addEventListener('abort',()=>console.log('Listener 2'),{once: true});// won't be recovered// Set onabort handleraborter.signal.onabort=()=>console.log('Onabort handler');},[]);consthandleFirstClick=()=>{// First abortaborter.abort('First reason');// Output:// Listener 1// Listener 2 (once)// Onabort handler// The signal is now a fresh one, but the non‑once listeners and onabort are reattachedaborter.signal.addEventListener('abort',()=>console.log('Listener 3'));// new listener, will survive next abort};consthandleSecondClick=()=>{// Second abortaborter.abort('Second reason');// Output:// Listener 1// Onabort handler// Listener 3};return(<div><buttononClick={handleFirstClick}>First abort</button><buttononClick={handleSecondClick}>Second abort</button></div>);};

πŸ“‹ License

MIT License - see LICENSE for details.

About

πŸš€ πŸ“© A library for canceling asynchronous requests with React integration

Topics

Resources

Code of conduct

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Contributors

Languages