debounce-hook-async
v1.0.5
Published
This is a custom hook used in React applications to delay a value by a certain amount of time. It also allows your functions to run asynchronously and handle possible errors.
Downloads
2
Readme
debounce-hook-async
This is a custom hook used in React applications to delay a value by a certain amount of time. It also allows your functions to run asynchronously and handle possible errors.
Installation
You can install the package in your project using npm or yarn:
npm install debounce-hook-async
# or
yarn add debounce-hook-async
Usage
Once you have added the package to your project, usage is straightforward. Here's a basic example:
import React, { useState } from 'react';
import useDebounceAsync from 'debounce-hook-async';
const MyComponent = () => {
const [inputValue, setInputValue] = useState('');
const { debouncedValue, error } = useDebounceAsync(inputValue, 500);
// Async operations with debouncedValue
// For example, fetching data from an API
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(`https://api.example.com/data?q=${debouncedValue}`);
if (!response.ok) {
throw new Error('API request failed');
}
const data = await response.json();
// Handle fetched data
} catch (error) {
// Handle error
}
};
if (debouncedValue) {
fetchData();
}
}, [debouncedValue]);
return (
<div>
<input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Type something..."
/>
{error && <p>Error: {error.message}</p>}
</div>
);
};
export default MyComponent;