rows/automata

Feature: ability to branch to next state based on the result of invoked callback

Closed this issue ยท 4 comments

Summary

When the src callback of the invoke element completes without problem, the automata unconditionally transitions into the target state specified in the angle brackets of onDone.

We would like an option to conditionally branch to a state based on the result of the invoked callback.

Acceptance criteria

  • ability to transition based on the result of the invoked callback
  • or any way to pass on the result of the invoked callback to the next state

Alright it seems that in XState, onDone can be an array of transitions with conditions:

invoke: {
    src: 'validateMobileNumber',
    onDone: [
      {
        target: 'valid',
        actions: assign({mobileNumberError: ''}),
        cond: (_ctx, event) => {
          const validationResponse = event.data;
          if (validationResponse.result) { // I don't know what's in your response... Just an example
            return true;
          } else {
            return false;
          }
        }
      },
      // If the condition is false, validation failed, so go to invalid
      {
        target: 'invalid',
        actions: assign((_ctx, event) => ({ mobileNumberError: event.data.validationMessage }))
      }
    ],
    onError: { ... }

Source: statelyai/xstate#850 (comment)

This makes total sense and I'll investigate if we can follow the same approach.

@91jaeminjo can you try to install from branch feat/12 and try to have multiple onDone entries with different conditions to see if it fits your needs? Check the test file in this PR #13 to see an example. If this fits your needs I'll make the PR ready for my team to review.

Just tried out the branch, and this is exactly what I needed! Thank you @canastro!

PR Merged and version 0.2.0 published. Thank you for your suggestion @91jaeminjo :)