#Raising an event as a consequence of an action

1 messages · Page 1 of 1 (latest)

rose hemlock
#

Curious if I'm running headlong into an antipattern here in my first try with xstate, specifically around the idea that actions are "fire-and-forget side-effects". Wondering what the boundaries are of that advice. I'm modeling an engine for a CLI as a state machine actor which bootstraps with an entry action on the initial state, which will eventually cause a transition to be fired. The way I've gotten this working so far is to use enqueueActions in the following manner:

 actions: {
   "checkStore": enqueueActions(({ enqueue }) => {
     console.log("Checking store");
     const checkStoreResult = 'foo';
     enqueue.raise(() => ({ type: 'storeChecked', data: checkStoreResult }));
   }),

My initial impulse was to define checkStore as an arbitrary function which would do stuff and then call raise itself when read, or perhaps to give that function a reference to the actor so it could send the storeChecked event, but the first idea didn't work (I've since realized that helper functions like raise and assign actually return an action definition, not cause the "effect"), and the second idea I haven't tried yet since it doesn't quite feel right. Is enqueueActions the right tool for the job in this sort of situation?

unique urchin
#

I don't think there's any need for enqueueActions if you only create a single action. If you expect checkStore to be async then an invoked fromPromise would be best, if it isn't async you can just put it in the lambda function that you supply to raise

#
{actions: {
    "checkStore": raise(() => {
const checkStore = 'foo' 

return { type: 'storeChecked', data: checkStoreResult }
    },} ```
#

With the async invocation, you would put the raise action in the invoked actor's onDone action and read the output value

rose hemlock
#

Ah, I understand -- didn't occur to me that I could expand raise's callback in that way. fromPromise sounds like something I need to understand better for some other parts of this project, but I'm stumbling a bit over the practical concept of actors in xstate. I thought invoking an actor was specifically something you would do to an actor defined from another statechart, but I'm starting to get the picture that an invokable actor is really a much more generic concept. I'm going to reread the docs about actors and see if I can make more sense of this.

unique urchin
#

createEmptyActor was what really helped me figure it out

#

Everything and anything can be an actor basically. createEmptyActor emits undefined once and is done, state machines are extremely defined and specific actors. Everything else falls between those two points