github statelyai/xstate xstate@4.17.0

latest releases: @xstate/svelte@3.0.5, @xstate/vue@3.1.4, @xstate/store@2.6.0...
3 years ago

Minor Changes

  • 7763db8d #1977 Thanks @davidkpiano! - The schema property has been introduced to the machine config passed into createMachine(machineConfig), which allows you to provide metadata for the following:

    • Context
    • Events
    • Actions
    • Guards
    • Services

    This metadata can be accessed as-is from machine.schema:

    const machine = createMachine({
      schema: {
        // Example in JSON Schema (anything can be used)
        context: {
          type: 'object',
          properties: {
            foo: { type: 'string' },
            bar: { type: 'number' },
            baz: {
              type: 'object',
              properties: {
                one: { type: 'string' }
              }
            }
          }
        },
        events: {
          FOO: { type: 'object' },
          BAR: { type: 'object' }
        }
      }
      // ...
    });

    Additionally, the new createSchema() identity function allows any schema "metadata" to be represented by a specific type, which makes type inference easier without having to specify generic types:

    import { createSchema, createMachine } from 'xstate';
    
    // Both `context` and `events` are inferred in the rest of the machine!
    const machine = createMachine({
      schema: {
        context: createSchema<{ count: number }>(),
        // No arguments necessary
        events: createSchema<{ type: 'FOO' } | { type: 'BAR' }>()
      }
      // ...
    });
  • 5febfe83 #1955 Thanks @davidkpiano! - Event creators can now be modeled inside of the 2nd argument of createModel(), and types for both context and events will be inferred properly in createMachine() when given the typeof model as the first generic parameter.

    import { createModel } from 'xstate/lib/model';
    
    const userModel = createModel(
      // initial context
      {
        name: 'David',
        age: 30
      },
      // creators (just events for now)
      {
        events: {
          updateName: (value: string) => ({ value }),
          updateAge: (value: number) => ({ value }),
          anotherEvent: () => ({}) // no payload
        }
      }
    );
    
    const machine = createMachine<typeof userModel>({
      context: userModel.initialContext,
      initial: 'active',
      states: {
        active: {
          on: {
            updateName: {
              /* ... */
            },
            updateAge: {
              /* ... */
            }
          }
        }
      }
    });
    
    const nextState = machine.transition(
      undefined,
      userModel.events.updateName('David')
    );

Don't miss a new xstate release

NewReleases is sending notifications on new releases.