Created
May 17, 2025 03:14
-
-
Save SandroMaglione/3ef1f83b212af1a15c4221d22b2ac3e3 to your computer and use it in GitHub Desktop.
State machine for a "copy text" button using `xstate`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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