menu

Statecharts

Statecharts are a precise, visual way of modeling the behaviour of complex reactive systems. They describe how things work, and can help you get your code doing exactly what you want.

Channels
Team

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 4 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) => {
console.log(event)
}
Thanks! Appreciate any ideas.

December 9, 2020 at 11:56pm
Hi!
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 event.data 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): https://xstate.js.org/docs/guides/communication.html#invoking-machines
Edited
  • 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) https://xstate.js.org/docs/guides/communication.html#done-data
  • 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