3

I have a simple state machine that handles an input form

export const chatMachine = Machine({
  id: 'chat',
  initial: 'idle',
  states: {
    idle: {
      on: {
        SET_MESSAGE: { actions: ['handleMessageChange'] },
        COMMENT_SUBMITTED: {
          actions: ['submitComment']
        }
      }
    }
  }
});

I would like the submitComment action to fire off a function and then reset a field in context like this:

submitComment: (ctx, e) => {
            e.payload(ctx.message);
            assign({
              message: ''
            });
          }

This doesn't work.

It fires the method I'm passing in but it doesn't make it to the assign bit.

Can I do two thing sin one action or should I be creating two seperate actions?

Josh Pittman
  • 7,024
  • 7
  • 38
  • 66

2 Answers2

4

You should be creating two separate actions because those are two separate actions.

I'm not sure what e.payload(ctx.message) does, but events should be purely data - you should not put functions in events.

Also, assign(...) is not imperative. It is a pure function that returns an action that looks something like { type: 'xstate.assign', ...}. None of XState's actions are imperative.

Try this:

// ...
COMMENT_SUBMITTED: {
  actions: ['submitComment', 'assignComment']
},

// ...
actions: {
  submitComment: (ctx, e) => { ... },
  assignComment: assign({ message: '' })
}
David Khourshid
  • 4,918
  • 1
  • 11
  • 10
0

Hit same problem today, finally get sth like this and that works perfect for me, you cannot use assign() in action but you could directly change the context

actions: {
  // ....
  changeToRemove: (context, event, meta) => {
    selection.value.color = 'red'
    context.selectionType = 'remove'
  },
  // ....
}

also try this with setTimeout(() => context.selectionType = 'remove', 2000) instead of simple assignment, but as expected when you fire sth that already use machine state before 2s then the old value is used so if you want to select sth from API or use some asynchronus actions maybe better solution is to add more states to the machine then after call action send event to the machine to change it state

Paweł Liszka
  • 330
  • 1
  • 2
  • 17