One of the most common feature requests Robot gets is the ability to run code when a state is entered, similar to XState entry actions. This is a valid request, and maybe something we’ll add some day, but you can actually already do this yourself in Robot.
Robot is built to be extensible, and it does so through the use of prototypical inheritance. Using prototypes is becoming a lost art in JavaScript today, and the way Robot does it is even more rare; Robot extends regular objects, not classes. All of the types within Robot work this way, from states to transitions. This means anything that inherits from these types can do what they do.
And one of the things states can do is run code when the state is entered. This is used for invoke, which is just a special type of state that can start up a submachine or wait on a promise and then send events back into the service.
This means you can implement your own entry functionality as well, but extending the state type. You can get the state type by calling the state() function. What you get is an object with a bunch of properties, one of them being a function called enter. You can’t override properties on Robot types, as they are frozen objects, but you can extend them with Object.create.
Here’s an example that increments a counter when you enter the green state. Here’s a simplified look at what happens:
let greenState = state((transition('change', 'yellow')));
let greenStateWithInc = Object.create(greenState, {
enter: {
value(machine, service) {
service.context.count++;
return machine;
}
}
});
const machine = createMachine({
green: greenStateWithInc
// ...
});
This is of course pretty verbose to write, which is why the example includes a function to do the cumbersome part for you:
const stateWithEntry = (fn) => (...args) =>
Object.create(state(...args), {
enter: {
value: fn
}
});
Which can then be used like so:
const incState = stateWithEntry((machine, service) => {
service.context.count++;
return machine;
});
Conclusion
It’s very valid to want a way to run entry actions in Robot, and as I said earlier, we might eventually add it. This article was written to show the way in which Robot works under the hood, to hopefully inspire you to know that you can achieve most of the things that you want to do already.
Most of this is not documented properly, and that’s why few people know that you can do it. But consider this article documentation, this pattern will always be supported in Robot.