by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
    David Khourshid
    @davidkpiano
    CleanShot 2020-07-14 at 10.11.16@2x.png
    5 replies
    Working on some new visuals!
    Frank Stallone
    @frankstallone

    Hello World! I am new to the state machine world and from my research want to move in this direction on a React app. In that vain, I am trying to wrap my head around a few concepts. Let's see if someone can help me figure this simplified problem I have out.

    Say I have a wrapper component that has children. While that component is 'loading' I want to have a loading screen displayed, and when childen are available, be 'idle'. Does that mean that instead of my starting point being 'idle', it's actually 'loading'? I am created a very simple viz @ https://xstate.js.org/viz/?gist=6c81cec4e6746016e54d1e7f25c624b5 that will expand as I get a few of these concepts solidified.

    7 replies
    Frank Stallone
    @frankstallone
    Another question related to React. We have a parent component that we gain context from for dispatching. In a specific component we add that context like this, const baseContext = React.useContext(BaseInputContext);, and that's just below where we are we useMachine, const [state, send] = useMachine(arrayListMachine);. Would the following be a valid way of doing this dispatching, in the React component, so that it only happens when the state.matches('sending')?
    if (state.matches('sending')) {
        baseContext.dispatch(action);
    }
    7 replies
    rxliuli
    @rxliuli
    It is recommended that the CodeSandbox template of xstate + react at least show how to modify the internal state of the react component, otherwise it is always subconscious to think that the state of xstate is self-contained, and it is not easy to know how to integrate it into an existing react application (now There are many states declared by react hooks/mobx in the react application)
    Attachment: Of course, now I know that I can modify the internal state of the component through actions, but why not put it to the beginning?
    1 reply
    EchoSysBen
    @BenoitDel
    Hello everybody, i don't understand why the actions are called only in the parent machine. You can find this behavior in the following codesandbox example.
    If you click on parent machine button the side effects are called and appear in the console , but if you click on child machine button side effects are not triggered.
    7 replies
    Frank Stallone
    @frankstallone
    Is keeping an <input>'s keystrokes in XState, with history, asking for trouble, or really more aligned with it's purpose?
    4 replies
    Stan Chang Khin Boon
    @lxcid_twitter
    is there a way to make a service wait from a dynamically generated child state machine? e.g. src is a function that return a machine?
    4 replies
    haywirez
    @a12i_gitlab
    version 4.11 is where it's at? i've been totally in the dark for the past few weeks
    1 reply
    Mark Melville
    @markmelville
    how can I reset a machine when I am using let [state, send] = useMachine(machine);?
    4 replies
    Mark Melville
    @markmelville
    To reset context, I'm trying this, but the context is not reset. What am I missing:
        success: {
          on: { "RESET": {
            target: "start",
            actions: assign(()=>({}))
          }}
        },
    10 replies
    Keith Layne
    @keithlayne
    I'm having sudden trouble with types of actor refs...previously I assigned typed the result of spawn(createMachine<A,B,C>) as Interpreter<A, StateSchema<unknown>, B, C>, but now it's a pretty deep type error. I had built these machines since upgrading to 4.11, but I had to do a bunch of changes, and I'm a little confused at this point. Any immediate thoughts?
    I think it's my fault though because of a helper type I added.
    Keith Layne
    @keithlayne
    spawn needed type args...that sucks.
    Yarden Bar
    @ayashjorden
    Can’t get the xstate.forwardTo action to work when using plain JSON to configure it.
    https://gitter.im/statecharts/statecharts?at=5efb6b25d65a3b0292bca1d4
    Any idea?

    Here is an example that does work in the XState-Viz https://xstate.js.org/viz/?gist=5a24c8c637ff6702a1f55d1d346e30a3

    Try sending {“type”:”FETCH”, “someOtherField”:1234567} and watch the browser cosole

    Keith Layne
    @keithlayne
    Has anyone done anything with actors in different JS contexts? I mean like a different window instance or node process or something. I've thought about having proxy machines that communicate over some kind of "transport" (for lack of better term) that could be abstracted, i.e window.postMessage or websockets or whatever. If anyone has done any work around something like this I'd be interested. I haven't really used erlang but the idea that actors are separated enough to be running anywhere is interesting...in that case the window/process/env kind of becomes implicit context, which is a little weird, but interesting.
    3 replies
    Yarden Bar
    @ayashjorden

    I read that the forwardTo action creator can only forward the event within the current state node (as per example and some experiment where It threw and exception if I specified an ID of invoke in another state-node

    Is there a way to relay current event to another state-node?

    BTW @davidkpiano, I did as discussed and render my MachineConfig throught a factory to replace actions that cannot be expressed using plain JSON, thank you

    34 replies
    Mikel Parra
    @mikelpmc

    Hi guys, I have a doubt regarding how to model some states.
    Imagine you have a very simple machine that fetches some data and you want to display two different "views" in your UI, a list if there is data and an empty state if there is not.

    What is better, to only have a "success" state and then do something like: status === 'success' and "no-data" > showEmptyState or could be a better option to have two different states, one for when you have data and one for when you have not.

    Thanks in advance.

    2 replies
    Mattias Holmlund
    @mattiash

    I am trying to understand the order that xstate executes different actions in. According to https://xstate.js.org/docs/guides/actions.html#action-order, actions are executed in the order

    1. exit actions
    2. transition actions
    3. entry actions

    Given the following state-machine:

    const fetchMachine = Machine({
      id: 'fetch',
      initial: 'idle',
      context: {
        count: 0
      },
      states: {
        idle: {
          entry: (context) => console.log(`entry ${context.count}`),
          exit: (context) => console.log(`exit ${context.count}`),
          on: {
            NEXT: {
              target: 'idle',
              actions: assign({
                count: (context) => {
                  console.log(`action ${context.count} => ${context.count+1}`)
                  return context.count + 1
                }
              })
            }
          }
        },
    }
    });

    I would expect it to log

    entry 0
    
    (NEXT)
    
    exit 0
    action 0 => 1
    entry 1
    
    (NEXT)
    
    exit 1
    action 1 => 2
    entry 2

    However, it logs

    entry 0
    
    (NEXT)
    
    action 0 => 1
    exit 1 
    entry 1 
    
    (NEXT)
    
    action 1 => 2 
    exit 2 
    entry 2

    I think this means that it executes the transition action before the exit action.
    This behaviour does not match how I interpret the documentation.
    I would like it to execute the exit action before the transition action so I can get an exit-action with the same context as the entry-action that came before it.
    How can I achieve this?

    3 replies
    Pat Cavit
    @tivac
    Can an invoked callback ever trigger the onDone for the invoke? Trying to expand on something @davidkpiano wrote to use invoked callbacks to allow for async loading of a child machine.
    2 replies
    Henry Snopek
    @hhsnopek

    hey all, can anyone explain how to 'combine' two state machines into one? ie, both state machines react to each other?
    I have a 'timer' which causes actions to occur in the other state machine, would it be best to combine these?

    this is a newer concept for me, if anyone has a moment to help me better understand a solution that'd be wonderful

    11 replies
    Just RAG
    @justrag
    Are there any xstate resources (a video, a blogpost) for designers? I mean, UX designers, like the guys that just use Figma and don't even really know HTML?
    3 replies
    Just RAG
    @justrag
    What's the most idiomatic way to enable a transition when all child parallel states are done? Do I need to dedicate a boolean piece of context for that, guard that transition with it, and flip it in an action in onDone?
    8 replies
    Aaron Moore
    @x-aaron-moore
    Is there a way to catch all errors from invokes in child states in a parent state? (Sorry to re-ask, I thought I'd answered my own question but am still struggling) Specifically, the error event that seems to be emitted is "xstate.platform.{invokeSrcName}" which would mean I'd still have to handle each of them... I've tried to catch them with a "*" event but that doesn't seem to match errors.
    6 replies
    Matt Pocock
    @mattpocock

    Hey all. I've been working on a codegen tool for getting 100% type safety on every part of an XState machine - state matching, actions, services etc.

    Here's what I've got so far:
    https://twitter.com/mpocock1/status/1288782560621928448

    5 replies
    Jim Redfern
    @jmredfern
    Hi :) When I persist my state from onTransition, and then restore it using interpret(machine).start(machine.resolveState(savedState)) the action associated with earlier event immediately fires. Does anyone know how to avoid it? (Same issue described here: https://spectrum.chat/statecharts/general/rehydrating-persisted-state-re-plays-action-already-executed-before-saving~24e02b83-d44f-49ab-898b-7ab1aaf46a25 ) --Thanks!
    4 replies
    Frank Stallone
    @frankstallone
    Do parents have access to children's history?
    6 replies
    joystick
    @joystick
    Hello, i'm accessing state using const [state] = useState(definition) in different react components. are they all referencing same machine instance according to machine's id?
    Docs say it will exist only for the lifetime of component. So in case if I would like to access existing service, created on root component, how should I reference it in child components? Thank you
    2 replies
    Tim
    @timothyallan
    Hey all, I really want to use xstate/fsm as I don't need any of the bigger xstate features. However, I do need to know when an event is fired, not just a state changed. Is this impossible without making an 'event' field in the context and populating it on each event?
    I see that the subscribe function only brings back state, so I am assuming that’d be the only way.
    2 replies
    haywirez
    @a12i_gitlab
    good docs example canditate: paginated fetch (if returns total pages, fetch x in parallel etc)
    haywirez
    @a12i_gitlab
    so much stuff to think about, keyset vs offset pagination etc.
    Just RAG
    @justrag
    Any particular patterns recommended for database-persisted objects? Or is it just: 1) get the object from database, 2) hydrate xstate context from the object , 3) perform transition, 4) update the object in db ?
    Lucas Hugdahl
    @qudo-lucas
    Hey, curious how you guys would handle this..I have a state machine that's handling a lot of GraphQL requests. I have a lot of invoke : { src : request(LONG QUERY STRING) }. Is there some feature of XState you guys would use to hold all of your GQL queries or even the requests themselves? Doing it all inline seems to improve readability but at the same time feels cluttered.
    Devin Weaver
    @sukima
    Yes, Name them and in your machine config (or .withConfig()) provide the actual implementations (under { services: {…} })
    This will allow you to debug, copy/paste to Viz, and mock easier in testing
    Let the machine define behavior with names, then provide the implementation after. I usually split implementation between machine focused (read pure) things like context conditionals and context manipulation as part of the initial machine config and then things that affect the outside world I link up using .withConfig()
    Example:
    function createMachine() {
      return Machine({
        id: …,
        initial: …,
        context: {},
        states: {
          foo: {
            entry: 'showLoadingIndicator',
            exit: 'hideLoadingIndicator',
            invoke: {
              src: 'myServiceName',
              onDone: { target: 'done', actions: 'storeResult' }
            }
          }
        }
      }, {
        actions: {
          storeResult: assign({ result: (_, evt) => evt.data })
        }
      });
    }
    let machine = interpret(createMachine().withConfig({
      actions: {
        showLoadingIndicator: () => {…},
        hideLoadingIndicator: () => {…}
      },
      services: {
        myServiceName: () => {…}
      }
    })).start();
    Lucas Hugdahl
    @qudo-lucas
    oh very cool. Looking into refactoring now. Thanks!
    David Khourshid
    @davidkpiano
    Let us know if you run into any issues with the refactor!
    Lidor Cohen
    @lidorcg_gitlab
    Hello everyone I'm trying to write some test for xstate machine with a "startup" phase which run automatically when the machine starts and eventually settles on a "ready" state where I would like to start my tests.
    It's kinda complex to do this in "onTransition" with conditions because "ready" is like a star state (we always return to it once a job is done) so it's not very nice to set variables to decide which test already ran and move on to the next. any ideas?
    9 replies
    haywirez
    @a12i_gitlab
    anyone succeeded in migrating a medium-complexity front-end app from redux + redux-saga to xstate? 😂
    David Khourshid
    @davidkpiano
    @a12i_gitlab any specific questions about it?
    Jack Anderson
    @JackCA
    @a12i_gitlab I did a high-complexity change from redux + redux-observable to xstate fwiw
    Aaron Moore
    @x-aaron-moore
    I've just gotten the basic shape of an event-source-persistence custom interpreter that uses mongodb to store the event streams. I think this looks like a viable path forward for our rehydration use case, however my team and I have some concerns around maintenance. How common has it been thus far for people to build custom interpreters? Is it difficult to keep up with xstate as it evolves? Also, in building my prototype it seems like the alternative API boundary that I'm integrating with could maybe be a little more thoroughly documented (such as, you will need to be able to handle 'xstate.start' and 'xstate.stop' actions for activities if you use any 'invoke's). (Which, so long as we continue along this path, I would be happy to help with)
    1 reply
    Fernando Montoya
    @montogeek
    I started with xstate 2 hours ago, is this approach correct?:
    const FlowParentComponent = () => {
       const [state, send, service] = useMachine(machine);
       if (state.matches("idle")) {
         return <CompStartMachine />
       }
    
        if (state.matches("state2")) {
         return <State2 service={service} />
       }
    
       // More ifs for parent states
    }
    
    const State2 = ({ service }) => {
      const [state, send] = useService(service);
    
     return <Element onClick={() => send('event')}>
    }
    Alternatively I could pass callbacks to send the events, so, all these state components are purely presentational
    Just RAG
    @justrag
    What's the statecharts notation used for sketch.systems and is there a conversion tool to xstate?