Created
May 19, 2025 03:19
-
-
Save SandroMaglione/666a5e07a5f5ab851285f4913bd34060 to your computer and use it in GitHub Desktop.
Input check debounce state machine 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
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