@coreui/react
Version:
UI Components Library for React.js
53 lines (50 loc) • 2.03 kB
JavaScript
import { __awaiter, __generator } from '../node_modules/tslib/tslib.es6.js';
import { useState, useCallback } from 'react';
/**
* useClipboard Hook
*
* Provides functionality to copy text to the clipboard and track the copy status.
*
* @returns An object containing the copy function, copy status, and any error encountered.
*/
var useClipboard = function () {
var _a = useState(false), isCopied = _a[0], setIsCopied = _a[1];
var _b = useState(null), error = _b[0], setError = _b[1];
/**
* Copies the provided text to the clipboard.
*
* @param text - The text to be copied to the clipboard.
*/
var copy = useCallback(function (text) { return __awaiter(void 0, void 0, void 0, function () {
var _error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(navigator === null || navigator === void 0 ? void 0 : navigator.clipboard)) {
setError(new Error('Clipboard API is not available'));
return [2 /*return*/];
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, navigator.clipboard.writeText(text)];
case 2:
_a.sent();
setIsCopied(true);
setError(null);
// Reset the isCopied state after 2 seconds
setTimeout(function () { return setIsCopied(false); }, 2000);
return [3 /*break*/, 4];
case 3:
_error_1 = _a.sent();
setError(_error_1);
setIsCopied(false);
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); }, []);
return { copy: copy, isCopied: isCopied, error: error };
};
export { useClipboard };
//# sourceMappingURL=useClipboard.js.map