UNPKG

@storm-stack/hooks

Version:

A collection of React hooks used by Storm Software in various client libraries and applications.

31 lines (30 loc) 992 B
import { EMPTY_STRING } from "@storm-stack/types/utility-types/base"; import { useCallback, useState } from "react"; function oldSchoolCopy(text) { const tempTextArea = document.createElement("textarea"); tempTextArea.value = text; document.body.appendChild(tempTextArea); tempTextArea.select(); document.execCommand("copy"); document.body.removeChild(tempTextArea); } export function useCopyToClipboard() { const [state, setState] = useState(null); const copyToClipboard = useCallback((value) => { const handleCopy = async () => { try { if (navigator?.clipboard?.writeText) { await navigator.clipboard.writeText(value ?? EMPTY_STRING); setState(value ?? EMPTY_STRING); } else { throw new Error("writeText not supported"); } } catch (e) { oldSchoolCopy(value ?? EMPTY_STRING); setState(value ?? EMPTY_STRING); } }; handleCopy(); }, []); return [state, copyToClipboard]; }