Created
May 13, 2025 10:11
-
-
Save SandroMaglione/eaed8580e105ac851fcd62a20797f67a to your computer and use it in GitHub Desktop.
Actor logic for a timer implemented 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 { assign, fromCallback, setup } from "xstate"; | |
type TickEvent = { type: "tick" }; | |
const timerLogic = fromCallback(({ sendBack }) => { | |
const timer = setInterval(() => { | |
sendBack({ type: "tick" } satisfies TickEvent); | |
}, 1000); | |
return () => { | |
clearInterval(timer); | |
}; | |
}); | |
const machine = setup({ | |
types: { | |
context: {} as { time: number }, | |
events: {} as TickEvent, | |
children: {} as { timer: "timer" }, | |
}, | |
actors: { timer: timerLogic }, | |
}).createMachine({ | |
context: { time: 0 }, | |
invoke: { src: "timer", id: "timer" }, | |
on: { | |
tick: { | |
actions: assign(({ context }) => ({ | |
time: context.time + 1, | |
})), | |
}, | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment