Skip to content

The one with txstate

Compare
Choose a tag to compare
@cassiozen cassiozen released this 28 Jul 19:51
· 25 commits to main since this release
a10dfcc

This release contains a implementation, porting and expanding on txstate library. It provides:

  • better error messages:

    Scenario 1


    Before -
    image
    image

    After -
    image
    image

    Scenario 2


    Before -
    image
    image

    After -
    image
    image

  • Typed guards hence inferring context typestates

    Example
    // example picked from xstate docs
    let [flightMachine] = useStateMachine<FlightMachineContext>({ trip: 'oneWay' })({
      initial: 'editing',
      states: {
        editing: {
          on: {
            SUBMIT: {
              target: 'submitted',
              guard: (context): context is FlightMachineSubmittedContext => {
                if (context.trip === 'oneWay') {
                  return !!context.startDate;
                } else {
                  return (
                    !!context.startDate &&
                    !!context.returnDate &&
                    context.returnDate > context.startDate
                  );
                }
              }
            }
          }
        },
        submitted: {}
      }
    })
    
    type FlightMachineEditingContext =
      { trip: 'oneWay' | 'roundTrip'
      , startDate?: Date
      , returnDate?: Date
      }
    type FlightMachineSubmittedContext =
      | { trip: 'oneWay'
        , startDate: Date
        }
      | { trip: 'roundTrip'
        , startDate: Date
        , returnDate: Date
        }
    
    type FlightMachineContext =
      | FlightMachineEditingContext
      | FlightMachineSubmittedContext
    
    expectType<FlightMachineContext>(flightMachine.context);
    if (flightMachine.value === 'submitted') {
      expectType<FlightMachineSubmittedContext>(flightMachine.context);
      
      if (flightMachine.context.trip === 'oneWay') {
        expectError(flightMachine.context.returnDate)
      }
    }
  • New API, without the curried function workaround and with better support for typed events.

Credits: This was possible by the amazing effort of @devanshj