Skip to content

Instantly share code, notes, and snippets.

@SandroMaglione
Created May 19, 2025 03:19
Show Gist options
  • Save SandroMaglione/666a5e07a5f5ab851285f4913bd34060 to your computer and use it in GitHub Desktop.
Save SandroMaglione/666a5e07a5f5ab851285f4913bd34060 to your computer and use it in GitHub Desktop.
Input check debounce state machine using `xstate` ⏱️
const debounceMachine = setup({
types: {
events: {} as { type: "edit"; text: string },
},
actors: {
check: fromPromise(
// 👇 Use `signal` to abort the promise if the user starts typing
({ input, signal }: { input: { text: string }; signal: AbortSignal }) =>
Promise.resolve(input.text)
),
},
}).createMachine({
initial: "Idle",
on: {
edit: {
// 👇 Add `.` to target internal `Editing` state
target: ".Editing",
},
},
states: {
Idle: {},
Editing: {
after: {
// 👇 Add 1 second delay before checking (debounce)
1000: "Checking",
},
},
Checking: {
// 👇 Async check using actor
invoke: {
src: "check",
input: ({ context }) => ({ text: context.text }),
onDone: "Idle",
},
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment