Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created October 24, 2020 22:27
Show Gist options
  • Save ryanflorence/e467ceb93fdba6814ef788dcbc9f00aa to your computer and use it in GitHub Desktop.
Save ryanflorence/e467ceb93fdba6814ef788dcbc9f00aa to your computer and use it in GitHub Desktop.
function CopyButton({ value }) {
let [copied, setCopied] = React.useState();
let hydrated = usePageIsHydrated();
React.useEffect(() => {
let id = setTimeout(() => setCopied(false), 2000);
return () => clearTimeout(id);
}, [copied]);
return (
<button
disabled={!hydrated}
onClick={() => {
navigator.clipboard.writeText(value);
setCopied(true);
}}
>
<ClipboardSvgIcon />
{copied ? "Copied!" : "Copy"}
</button>
);
}
@harry830622
Copy link

I'm not really sure, but won't the effect be executed twice? One time triggered when copied is set to true, and another time when copied is set to false which will make copied to false again (but won't cause another effect since the value didn't change)
I don't think it affects much, just a point there

Yes, I think you are right.
It just happens to be fine in this case.
Adding a if (copied) clause may be better.

@osamasayed
Copy link

Do you mind sharing usePageIsHydrated?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment