conditional-statementsstatetargetstate-machinexstate

How to run action first, then conditionally target in xstate


I am using xState app machines and I am finding myself needing to do things in sequence. Below when I fir NAV_OK, I want it to run the action 'run-search' first, then after it runs, I want it to focus automatically on the correct element based on some guard/condition. It seems to be choosing them instead. Unfortunately I cannot move the action 'run_search' into each target block, as I need it to run before it deals with those.

 NAV_OK: [
                //run the search and return products/videos
                { actions: 'run_search' },
                {

                  //if products exists focus on that swimlane
                  target: 'products',
                  cond: (ctx) => ctx.products > 0

                },
                {
                  //if videos exists focus on that swimlane
                  target: 'videos',
                   cond: (ctx) => ctx.videos > 0

                }

              ],

Solution

  • I ended up creating another state where I handled the run_search then I used a weird xstate '' thing called transient transition.

    newState: {
                id: 'newState',
                entry: 'run_search',
                on: {
                 '': [
                    {
                        cond:(ctx) => ctx.products > 0,
                        target:'products',
                    },
                    {
                        cond:(ctx) => ctx.videos > 0,
                        target: 'videos',
                                        
                    },
                    {
                        target: 'idle'
                    }
                   ]
                  }
                 }