lache
lache

Reputation: 830

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

                }

              ],

Upvotes: 2

Views: 4209

Answers (1)

lache
lache

Reputation: 830

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'
                }
               ]
              }
             }

Upvotes: 1

Related Questions