Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useState, useEffect } from 'react';
- /**
- * Debounce async functions
- * initialValue will be returned debounced in the callback.
- *
- * @param {(initialValue: any) => <Promise>} asyncCallback A function that returns a promise
- * @param {any} initialValue Initial value to be debounced
- * @param {number} delay Number of miliseconds for debouncing
- */
- export default function useDebounceAsync(asyncCallback, initialValue, delay = 500) {
- const [value, setValue] = useState(initialValue);
- const [debouncedValue, setDebouncedValue] = useState(value);
- const [isLoading, setIsLoading] = useState(false);
- const [results, setResults] = useState([]);
- useEffect(
- () => {
- const handler = setTimeout(() => {
- setDebouncedValue(value);
- }, delay);
- return () => {
- clearTimeout(handler);
- };
- },
- [value],
- );
- useEffect(
- () => {
- const fetch = async () => {
- if (debouncedValue) {
- setIsLoading(true);
- const res = await asyncCallback(debouncedValue);
- setIsLoading(false);
- setResults(res);
- } else {
- setResults([]);
- }
- };
- fetch();
- },
- [debouncedValue],
- );
- return { results, setValue, isLoading };
- }
- /**
- Usage: const { results, setValue } = useDebounceAsync((debouncedValue) => {
- return api({ searchValue: debouncedValue });
- }, '');
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement