2021-02-04 19:15:23 +01:00
|
|
|
import { useState, useCallback } from 'react';
|
|
|
|
import copyToClipboard from 'copy-to-clipboard';
|
2021-06-10 21:27:03 +02:00
|
|
|
import { SECOND } from '../../shared/constants/time';
|
2021-02-04 19:15:23 +01:00
|
|
|
import { useTimeout } from './useTimeout';
|
2020-07-24 16:17:03 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* useCopyToClipboard
|
|
|
|
*
|
2020-11-10 18:30:41 +01:00
|
|
|
* @param {number} [delay=3000] - delay in ms
|
2022-01-07 16:57:33 +01:00
|
|
|
* @returns {[boolean, Function]}
|
2020-07-24 16:17:03 +02:00
|
|
|
*/
|
2021-06-10 21:27:03 +02:00
|
|
|
const DEFAULT_DELAY = SECOND * 3;
|
2020-07-24 16:17:03 +02:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export function useCopyToClipboard(delay = DEFAULT_DELAY) {
|
2021-02-04 19:15:23 +01:00
|
|
|
const [copied, setCopied] = useState(false);
|
|
|
|
const startTimeout = useTimeout(() => setCopied(false), delay, false);
|
2020-07-24 16:17:03 +02:00
|
|
|
|
|
|
|
const handleCopy = useCallback(
|
|
|
|
(text) => {
|
2021-02-04 19:15:23 +01:00
|
|
|
setCopied(true);
|
|
|
|
startTimeout();
|
|
|
|
copyToClipboard(text);
|
2020-07-24 16:17:03 +02:00
|
|
|
},
|
|
|
|
[startTimeout],
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
2020-07-24 16:17:03 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
return [copied, handleCopy];
|
2020-07-24 16:17:03 +02:00
|
|
|
}
|