@coreui/react
Version:
UI Components Library for React.js
55 lines (51 loc) • 2.06 kB
JavaScript
var tslib_es6 = require('../node_modules/tslib/tslib.es6.js');
var React = require('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 = React.useState(false), isCopied = _a[0], setIsCopied = _a[1];
var _b = React.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 = React.useCallback(function (text) { return tslib_es6.__awaiter(void 0, void 0, void 0, function () {
var _error_1;
return tslib_es6.__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 };
};
exports.useClipboard = useClipboard;
//# sourceMappingURL=useClipboard.js.map
;