lodash#DebouncedFunc TypeScript Examples

The following examples show how to use lodash#DebouncedFunc. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useDebouncedCallback.ts    From jitsu with MIT License 6 votes vote down vote up
useDebouncedCallback = <T extends (...args: any[]) => unknown>(
  callback: T,
  delay: number
): DebouncedFunc<T> => {
  // ...
  const inputsRef = useRef({ callback, delay })
  const isMounted = useIsMounted()

  useEffect(() => {
    inputsRef.current = { callback, delay }
  }, [callback, delay])

  return useCallback<DebouncedFunc<T>>(
    debounce<T>(
      ((...args) => {
        // Debounce is an async callback. Cancel it, if in the meanwhile
        // (1) component has been unmounted (see isMounted in snippet)
        // (2) delay has changed
        if (inputsRef.current.delay === delay && isMounted()) inputsRef.current.callback(...args)
      }) as T,
      delay
    ),
    [delay, debounce]
  )
}
Example #2
Source File: UsernameInput.tsx    From frontend.ro with MIT License 5 votes vote down vote up
function UsernameInput({ name }: any) {
  const ref = useRef<HTMLInputElement>(null);
  const checkFn = useRef<DebouncedFunc<(value: string) => void>>(debounce(checkUsername, 250));

  const [username, setUsername] = useState(null);
  const [usernameExists, setUsernameExists] = useState(undefined);

  const onUsernameChange = (e) => {
    let value: string = e.target.value ?? '';
    value = value.trim();

    setUsername(value);
    setUsernameExists(undefined);

    if (!value) {
      return;
    }

    checkFn.current.cancel();
    checkFn.current(value);
  };

  function checkUsername(value: string) {
    return UserService.checkUsername(value)
      .then(() => {
        setUsernameExists(true);
        ref.current.setCustomValidity('Acest username există deja');
      })
      .catch(() => {
        ref.current.setCustomValidity('');
        setUsernameExists(false);
      });
  }

  return (
    <InputWithIcon
      required
      type="text"
      name={name}
      ref={ref}
      onChange={onUsernameChange}
    >
      {usernameExists && <FontAwesomeIcon width="1em" className="text-red" icon={faTimes} />}
      {usernameExists === false && <FontAwesomeIcon width="1em" className="text-green" icon={faCheck} />}
      {usernameExists === undefined && username && <FontAwesomeIcon width="1em" className="rotate" icon={faSpinner} />}
    </InputWithIcon>
  );
}
Example #3
Source File: Login.tsx    From frontend.ro with MIT License 5 votes vote down vote up
private checkUsernameDebouncedFn: DebouncedFunc<() => void>;