useinputdebounce

1.0.0 • Public • Published

A custom React Hook for debouncing user inputs on Input and Textarea elements.

useInputDebounce

Build Status

Installation

npm install --save useinputdebounce

Example

import React, { useState } from "react";
import ReactDOM from "react-dom";
import useInputDebounce from "useinputdebounce";
 
function App() {
  const [results, setSearch] = useState([]);
 
  const effect = async (value, setValue) => {
    const res = await searchCharacters(value);
    setSearch(res);
  };
 
  const attributes = useInputDebounce(effect, { delay: 200, minLength: 1 });
 
  return (
    <div>
      <input {...attributes} placeholder="Search Country..." />
      {results.map(result => (
        <div key={result.name}>
          <h2>{result.name}</h2>
        </div>
      ))}
    </div>
  );
}
 
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
 
function searchCharacters(search) {
  return fetch(`https://restcountries.eu/rest/v2/name/${search}`)
    .then(r => r.json())
    .then(r => (r.status !== 404 ? r : []))
    .catch(error => []);
}

CodeSandbox Example

API Reference

const { value, onChange } = useInputDebounce(sideEffect, [opts])
  • sideEffect: a function that will be excuted after a delay. You can perform actions like fetching data.
  • opts: an object whose values can be { delay, minLength, initial }

License

This software is free to use under the MIT license. See the LICENSE file for license text and copyright information.

Dependencies (0)

    Dev Dependencies (26)

    Package Sidebar

    Install

    npm i useinputdebounce

    Weekly Downloads

    1

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    9.66 kB

    Total Files

    8

    Last publish

    Collaborators

    • iusehooks