mirror of
https://github.com/documenso/documenso.git
synced 2025-11-12 07:43:16 +10:00
29 lines
740 B
TypeScript
29 lines
740 B
TypeScript
import { useState } from 'react';
|
|
|
|
export type CopiedValue = string | null;
|
|
export type CopyFn = (_text: string) => Promise<boolean>;
|
|
|
|
export function useCopyToClipboard(): [CopiedValue, CopyFn] {
|
|
const [copiedText, setCopiedText] = useState<CopiedValue>(null);
|
|
|
|
const copy: CopyFn = async (text) => {
|
|
if (!navigator?.clipboard) {
|
|
console.warn('Clipboard not supported');
|
|
return false;
|
|
}
|
|
|
|
// Try to save to clipboard then save it in the state if worked
|
|
try {
|
|
await navigator.clipboard.writeText(text);
|
|
setCopiedText(text);
|
|
return true;
|
|
} catch (error) {
|
|
console.warn('Copy failed', error);
|
|
setCopiedText(null);
|
|
return false;
|
|
}
|
|
};
|
|
|
|
return [copiedText, copy];
|
|
}
|