JSPM

use-debounce-fetch

1.0.9
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 7
  • Score
    100M100P100Q37859F
  • License ISC

"Debounce fetch and abort previous pending requests"

Package Exports

  • use-debounce-fetch
  • use-debounce-fetch/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (use-debounce-fetch) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

use-debounce-fetch

A React Hook to debounce fetch requests and abort previous pending requests made by this hook.

Features

  • Debounce duplicate requests such as when searching
  • Abort pending requests made previously using this hook
  • Swallows error "The user aborted a request" for previously aborted requests
  • Eliminates need for a debounced input

Install via npm

   npm install use-debounce-fetch

Usage

import useDebounceFetch from 'use-debounce-fetch'

export const RepoSearch  = ()=>{

    const debounceFetch = useDebounceFetch(400);
    const [results, setResults] = useState([]);

    const search = async e =>{
        const {value} = e.target;
        if(value){
            const res = await debounceFetch('https://api.github.com/search/repositories?q='+value);
            const data = await res.json();
            setResults(data.items);
        }else{
            debounceFetch.cancel();
            setResults([]);
        }
    }
    
    return (
        <div>
            <input onChange={search}/>
            <h3>Results</h3>
            {results.map((item, index)=>(
                <div key={index}>{item.name}</div>
            ))}
        </div>
    );
}

API

useDebounceFetch( [ wait=0 ], [ options={} ], [ fetchFunc=fetch ])

  • wait [number=0] The number of milliseconds to delay.
  • options [object={}] Lodash.debounce options object. See _.debounce
  • fetchFunc [Function=fetch] The fetch library (function) to use under the hood. Defaults to native fetch. (Needs to reject with errorcode 20 when request is aborted for this hook to swallow those errors)

Peer dependencies

  • react >=16.8.2