The Statecharts community on Spectrum is (along with spectrum) MOVING TO OTHER PLATFORMS: For statecharts discussions in general go to Statecharts Discussion on GitHub or Gitter( For XState-specific questions, go to the XState discussion forum for Q&A or the Stately discord chat to chat.


Is there an easy way to return a value from a finished machine in the…

December 9, 2020 at 9:21pm

Is there an easy way to return a value from a finished machine in the Interpreter's .onDone() function?

December 9, 2020 at 9:21pm (Edited 5 months ago)
I have a machine like this...and It runs a bunch of calculations, one of which I'd like to surface, and access inside the service.onDone() method. I see that the 'final' event is sent along, but since my machine is just doing calculations, I'm not really using any Events internally, just using always inside my states with guards to transition.
let buyAmountMachine = createBuyAmountMachineWithContext({ tx, logger })
const service = interpret(buyAmountMachine)
.onTransition((state) => console.log(`Transitioned to ${state.value}`))
.onDone((event) => {
Thanks! Appreciate any ideas.

December 9, 2020 at 11:56pm
You can easily return data by adding the data property to your final state, like so:
finalState: {
type: 'final',
data: {
my: 'data'
You can then use in the onDone() callback.
You can read more here (even though you're not invoking this machine from another machine, it's the same thing):
  • reply
  • like
Felix is totally right, just to be more specific: I think you're going to need a function to extract the data: data : (context, event) => context.finalResult See (just a few paragraphs down from (felix-guerin)'s link)
  • reply
  • like

December 10, 2020 at 4:14pm
(felix-guerin) (reedspool) ahhh Exactly what I needed! You guys are the best =) So does this mean that the root node is basically just an invoked machine?
  • reply
  • like
By root node are you referring to the service? The service is a wrapper around your machine. Machine's don't actually do anything, they just produce lists of actions to take when sent an event. Some other caller needs to send the events and call those actions. Service is one such caller but you could write your own.
  • reply
  • like