Visualize

your State Management with XState

Maya Shavin - Vue Verona 2022

@mayashavin

@mayashavin

On bus

Check-in

Arrive by air

Arrive to station

Reach the hotel

Travel by train

State Management

  • Manage conditions of an app/ component/ feature at a given session period.
  • Keep consistency of data flows.

@mayashavin

@mayashavin

When something happens, how do the app react?

Events

Behaviors (states)

@mayashavin

State

State 

State 

Event

Event

Event

Finites of States

Transition using Event

State data control using Actions

@mayashavin

State machine

@mayashavin

Translate the diagram into actual code?

How many lines of if...else if... (or switch...case) is enough?

@mayashavin

The JS State Machines Library

@mayashavin

npm i xstate @xstate/vue
const fetchMachine = createMachine({
    id: 'fetch',
    initial: 'idle',
    context: { retries: 0 },
    states: {
      idle: {
        on: {
          FETCH: 'loading'
        }
      },
      loading: {
        on: {
          RESOLVE: 'success',
          REJECT: 'failure'
        }
      },
      success: {
        type: 'final'
      },
      failure: {
        on: {
          RETRY: {
            target: 'loading',
            actions: assign({
              retries: (context, event) => context.retries + 1
            })
          }
        }
      }
    }
  });

@mayashavin

import { interpret } from 'xstate';

const machine = createMachine({/* configuration */})

const service = interpret(machine)

service.onTransition(newState => {
/* do something during transition from one state to another */
}).start();

service.send('EVENT');
import { myMachine } from '../machines/myMachine';
import { interpret } from "xstate";
import { useActor } from '@xstate/vue'

const service = interpret(myMachine).start()
export default {
  setup() {
    const { state, send } = useActor(service)
    
    const transition = () => send('EVENT')
    
    return { state, transition }
  }
}

Vue

Demo

Seeing is believing... as always

@mayashavin

Vue 3
Pinia
XState
XState/vue
XState/inspect
XState/graph

Requirements

  • Define state machine Wizard for cart checking out cart
  • Visualize the state machine for wizard steps
  • Guarding steps with condition (shipping address)
  • Auto generate visual flow for the wizard

@mayashavin

reading IS understanding

Visualizing

@mayashavin

Why Xstate?

@mayashavin

  • Separate machine logic that can be reused everywhere 
  • Keep the UI isolated
  • Easy to modify states
  • Readability
  • Easy to test & maintain
  • Lightweight & can combine with other libraries (Pinia)
  • Easy to visualize and plan ahead

XState Machine Editor

@mayashavin

Plan first, code later

@mayashavin

REsources

@mayashavin

A LITTLE BIT about me

Senior Software Engineer

MICROSOFT

Core Team

STOREFRONT-UI

Organizer

VUEJS ISRAEL

Blogger & Book Author

@mayashavin

mayashavin.com

Thank you

@mayashavin

mayashavin.com

Made with Slides.com