intro Xstate

Finite State Machine

what is FSM?

  • Finite number of states
  • Initial state
  • Finite number of events
  • Transitions
  • Final states

Using switch/case

function transition(state, event) {
  switch (state) {
    case 'idle':
      switch (event) {
        case 'FETCH':
          return 'pending';
        default:
          return state;
      }
    case 'pending':
      switch (event) {
        case 'RESOLVE':
          return 'resolved';
        case 'REJECT':
          return 'rejected';
        default:
          return state;
      }
    default:
      return state;
  }
}

Using objects

import { Machine } from 'xstate';

const fetchMachine = Machine({
  id: 'fetch',

  initial: 'idle',

  states: {
    idle: {
      on: {
        FETCH: 'pending'
      }
    },
    pending: {
      on: {
        RESOLVE: 'resolved',
        REJECT: 'rejected'
      }
    },
    resolved: {
      type: 'final'
    },
    rejected: {}
  }
});

StateChart

 1984 年 David HAREL

  • 層級(hierarchy)
  • 併發(concurrency)
  • 通訊(communication)

intro Xstate

By jaokuohsuan

intro Xstate

  • 840