Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. import { useState, useEffect } from 'react';
  2.  
  3. /**
  4. * Debounce async functions
  5. * initialValue will be returned debounced in the callback.
  6. *
  7. * @param {(initialValue: any) => <Promise>} asyncCallback A function that returns a promise
  8. * @param {any} initialValue Initial value to be debounced
  9. * @param {number} delay Number of miliseconds for debouncing
  10. */
  11. export default function useDebounceAsync(asyncCallback, initialValue, delay = 500) {
  12. const [value, setValue] = useState(initialValue);
  13. const [debouncedValue, setDebouncedValue] = useState(value);
  14. const [isLoading, setIsLoading] = useState(false);
  15. const [results, setResults] = useState([]);
  16.  
  17. useEffect(
  18. () => {
  19. const handler = setTimeout(() => {
  20. setDebouncedValue(value);
  21. }, delay);
  22. return () => {
  23. clearTimeout(handler);
  24. };
  25. },
  26. [value],
  27. );
  28.  
  29. useEffect(
  30. () => {
  31. const fetch = async () => {
  32. if (debouncedValue) {
  33. setIsLoading(true);
  34. const res = await asyncCallback(debouncedValue);
  35. setIsLoading(false);
  36. setResults(res);
  37. } else {
  38. setResults([]);
  39. }
  40. };
  41. fetch();
  42. },
  43. [debouncedValue],
  44. );
  45.  
  46. return { results, setValue, isLoading };
  47. }
  48.  
  49. /**
  50.  
  51. Usage: const { results, setValue } = useDebounceAsync((debouncedValue) => {
  52. return api({ searchValue: debouncedValue });
  53. }, '');
  54.  
  55. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement