Xstate: How to get side effects from actions

Created on 19 Nov 2018  路  6Comments  路  Source: davidkpiano/xstate

Thanks for the new V4 release, awesome! I try to use the built-in interpreter and have a question. My understanding is that when you send an event, the interpreter executes the involved actions. But how do you get the side effects? through context? or should I write my own interpreter for that?

documentation question

All 6 comments

Thanks! What do you mean by "getting the side effects"?

All side effects (by definition) are fire-and-forget; they happen and generally should not affect the state of the machine.

If it's something different than that, there's probably a different way to handle it.

Thanks for the prompt reply, David! What I mean by "side effect" is seen in your article about Flickr Gallery handled by the command function. So it goes like this:

  1. the fetchJsonp function issues a call to the transition function with an action object:
    this.transition({ type: 'SEARCH_SUCCESS', items: data.items });
  2. the transition function transitions to the new state, and then calls the command function
  3. the command function returns { items: action.items } (this is where I see the term 'side effect' and 'extended state' used together.
  4. the transition function calls setState with the returned result from command.
    With release 4, what is the recommended approach to pass result handled by functions like the command? Thanks.

I need to rewrite that article; it's not up to date anymore. Sorry!

... what is the recommended approach to pass result handled by functions like the command?

If the functions are true side-effects, it's recommended to _not_ return anything from those functions (that is, their return type should be void).

If you need the return value of the function to change the extended state (context) of the machine, then use assign(): https://xstate.js.org/docs/guides/context.html

Otherwise, if you need to communicate (async) with some other service, use invoke: https://xstate.js.org/docs/guides/communication.html

Could you clarify the difference between side effect and extended state?
Regarding the Flickr Gallery example, it would be great to see that updated and included in the doc. Again thanks for a very detailed tutorial there, it helped a lot!
Should I use assign() outside of the interpreter, or call it from inside? I am hesitant in using context because I would still need to update React state later on.
Would you recommend using assign() or 'invoke' to fetch the pix in the Flickr example?

I'll update the Flickr example soon - will be more idiomatic.

Closing as this is in the docs. You can also see the side effects returned from actions in the state.actions array.

Was this page helpful?
0 / 5 - 0 ratings