diff --git a/src/hooks/useCopy.ts b/src/hooks/useCopy.ts new file mode 100644 index 0000000..54d0c51 --- /dev/null +++ b/src/hooks/useCopy.ts @@ -0,0 +1,28 @@ +import { isEmpty, isNil } from 'lodash-es'; +import { useCallback, useEffect } from 'react'; +import { useCopyToClipboard } from 'react-use'; +import { NotificationType, useNotification } from '../components/Notifications'; + +export function useCopy() { + const { showToast } = useNotification(); + const [cpState, copyToClipboard] = useCopyToClipboard(); + const copyAction = useCallback((content: string) => { + if (isNil(content) || isEmpty(content)) return; + copyToClipboard(content); + }, []); + + useEffect(() => { + if (!isNil(cpState.error)) { + showToast(NotificationType.ERROR, 'Failed to copy to clipboard', 'tabler:alert-circle', 3000); + } else if (!isNil(cpState.value)) { + showToast( + NotificationType.SUCCESS, + `Content copied to clipboard.`, + 'tabler:circle-check', + 3000, + ); + } + }, [cpState]); + + return copyAction; +}