A custom React Hook for debouncing user inputs on Input and Textarea elements.
npm install --save useinputdebounce
import React, { useState } from "react";
import ReactDOM from "react-dom";
import useInputDebounce from "useinputdebounce";
function App() {
const [results, setSearch] = useState([]);
const effect = async (value, updateValue) => {
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 => []);
}
- Fetching Data: Sandbox
const { value, onChange } = useInputDebounce(effect, { opts });
These should be applied to your input element.
- value: current input value
- onChange(): called on input value change
effect
: The function you wish to execute after the debounce delay.- Arguments: value, updateValue(). These arguments will be passed to your effect function when it is called by useInputDebounce after the delay (see example above).
- value: a string with the current value of the input
- updateValue(string): a function allowing you to update the input value after debounce delay
- Arguments: value, updateValue(). These arguments will be passed to your effect function when it is called by useInputDebounce after the delay (see example above).
opts
: An object whose properties can be { delay, minLength, initial }- default values:
- delay: 0 (zero)
- minLength: 0 (zero)
- initial: no initial value (undefined)
- default values:
This software is free to use under the MIT license. See the LICENSE file for license text and copyright information.