matteok
matteok

Reputation: 2189

perform action after every other action while in a speicific state

Let's say I have a machine with a single state that provides actions increment or decrement a value.

const Machine({
    id: 'some_machine',
    initial: 'initial',
    context: {
        value: 0
    },
    states: {
        'initial': {
            on: {
                'inc': {
                    actions: assign({
                        value: (ctx) = {
                            return ctx.value + 1
                        }    
                    })
                },
                'dec': {
                    actions: assign({
                        value: (ctx) = {
                            return ctx.value - 1
                        }    
                    })
                }
            }
        }
    }
} 

Is it possible to somehow specify an action in initial that maps the context after any other action is executed? As an example I might want to multiply the result of inc and dec every time.

I realize I could just add an action after both inc and dec but am interested if this is somehow doable in a single place.

Upvotes: 0

Views: 46

Answers (1)

David Khourshid
David Khourshid

Reputation: 5203

Essentially, you want to do two things:

  1. Execute an action (e.g., multiplying) whenever you enter a specific state
  2. Re-enter that specific state whenever some events (e.g., 'inc' and 'dec') happen.

Define an entry action on the 'initial' state, and target: 'initial' in order to re-enter that state (even though you're already in that state):

Machine({
  id: "some_machine",
  initial: "initial",
  context: {
    value: 0
  },
  states: {
    initial: {
      entry: assign({
        value: ctx => ctx.value * 2
      }),
      on: {
        inc: {
          target: "initial",
          actions: assign({
            value: ctx => {
              return ctx.value + 1;
            }
          })
        },
        dec: {
          target: "initial",
          actions: assign({
            value: ctx => {
              return ctx.value - 1;
            }
          })
        }
      }
    }
  }
});

Upvotes: 2

Related Questions