Create useClipboard hook
This commit is contained in:
parent
ec91b08514
commit
bcac693f88
2 changed files with 41 additions and 9 deletions
30
src/hooks/useClipboard.ts
Normal file
30
src/hooks/useClipboard.ts
Normal file
|
@ -0,0 +1,30 @@
|
|||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
function useClipboard(): [boolean, (text: string) => void] {
|
||||
const [copied, setCopyStatus] = useState(false);
|
||||
const timeout = useRef(null);
|
||||
|
||||
const clear = () => {
|
||||
if (timeout.current) {
|
||||
clearTimeout(timeout.current);
|
||||
timeout.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const copy = (text: string) => {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
setCopyStatus(true);
|
||||
timeout.current = setTimeout(() => {
|
||||
clear();
|
||||
setCopyStatus(false);
|
||||
}, 2000);
|
||||
});
|
||||
};
|
||||
|
||||
// Clear timeout after hook unmounting
|
||||
useEffect(() => clear, []);
|
||||
|
||||
return [copied, copy];
|
||||
}
|
||||
|
||||
export default useClipboard;
|
|
@ -9,6 +9,7 @@ import Typography from "@material-ui/core/Typography";
|
|||
import CloseIcon from "@material-ui/icons/Close";
|
||||
import { makeStyles } from "@material-ui/styles";
|
||||
import Link from "@saleor/components/Link";
|
||||
import useClipboard from "@saleor/hooks/useClipboard";
|
||||
import React from "react";
|
||||
import { FormattedMessage } from "react-intl";
|
||||
|
||||
|
@ -55,13 +56,10 @@ const useStyles = makeStyles(
|
|||
}
|
||||
);
|
||||
|
||||
function handleCopy(token: string) {
|
||||
navigator.clipboard.writeText(token);
|
||||
}
|
||||
|
||||
const ServiceDefaultToken: React.FC<ServiceDefaultTokenProps> = props => {
|
||||
const { apiUri, token, onApiUriClick, onTokenClose } = props;
|
||||
const classes = useStyles(props);
|
||||
const [copied, copy] = useClipboard();
|
||||
|
||||
return (
|
||||
<Card className={classes.root}>
|
||||
|
@ -98,12 +96,16 @@ const ServiceDefaultToken: React.FC<ServiceDefaultTokenProps> = props => {
|
|||
<Button
|
||||
className={classes.copy}
|
||||
color="primary"
|
||||
onClick={() => handleCopy(token)}
|
||||
onClick={() => copy(token)}
|
||||
>
|
||||
{copied ? (
|
||||
<FormattedMessage defaultMessage="Copied" description="button" />
|
||||
) : (
|
||||
<FormattedMessage
|
||||
defaultMessage="Copy token"
|
||||
description="button"
|
||||
/>
|
||||
)}
|
||||
</Button>
|
||||
</Paper>
|
||||
</CardContent>
|
||||
|
|
Loading…
Reference in a new issue