UNPKG

@ducor/hooks

Version:

A collection of useful React hooks for building modern web applications. Includes hooks for clipboard operations, window events, intervals, timeouts, and more.

61 lines (60 loc) 2.07 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import copy from "copy-to-clipboard"; import { useCallback, useEffect, useState } from "react"; const isNumber = (value) => { return typeof value === 'number' && !isNaN(value); }; const isString = (value) => { return typeof value === 'string'; }; /** * `useClipboard` is a custom hook that performs the operation of copying a value to the clipboard. * * @see Docs https://ui.ducor.net/hooks/use-clipboard */ const useClipboard = (defaultValue = "", timeoutOrOptions = {}) => { const [hasCopied, setHasCopied] = useState(false); const [value, setValue] = useState(defaultValue); useEffect(() => setValue(defaultValue), [defaultValue]); const _a = isNumber(timeoutOrOptions) ? { timeout: timeoutOrOptions } : timeoutOrOptions, { timeout = 1500 } = _a, copyOptions = __rest(_a, ["timeout"]); const onCopy = useCallback((newValue) => { if (!isString(newValue)) { newValue = value; } else { setValue(newValue); } const hasCopied = copy(newValue, copyOptions); setHasCopied(hasCopied); }, [value, copyOptions]); useEffect(() => { let timeoutId = null; if (hasCopied) timeoutId = window.setTimeout(() => { setHasCopied(false); }, timeout); return () => { if (timeoutId) window.clearTimeout(timeoutId); }; }, [timeout, hasCopied]); return { hasCopied, setValue, value, onCopy, }; }; export default useClipboard;