Skip to content

Instantly share code, notes, and snippets.

@SandroMaglione
Created May 17, 2025 03:14
Show Gist options
  • Save SandroMaglione/3ef1f83b212af1a15c4221d22b2ac3e3 to your computer and use it in GitHub Desktop.
Save SandroMaglione/3ef1f83b212af1a15c4221d22b2ac3e3 to your computer and use it in GitHub Desktop.
State machine for a "copy text" button using `xstate`
import { useActor } from "@xstate/react";
import { setup } from "xstate";
const copyMachine = setup({
types: {
events: {} as { type: "copy"; text: string },
},
}).createMachine({
initial: "Idle",
states: {
Idle: {
on: {
copy: {
target: "Copied",
actions: ({ event }) => {
window.navigator.clipboard.writeText(event.text);
},
},
},
},
Copied: {
after: {
2000: "Idle",
},
},
},
});
export default function CopyLink() {
const [snapshot, send] = useActor(copyMachine);
return (
<button onClick={() => send({ type: "copy", text: "some text" })}>
{snapshot.matches("Copied") ? "Copied!" : "Copy link"}
</button>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment