xstate

XState.js How to send context to a machine?


I am new to XState.js.

I want to use a simple ID in my context. How do I update the context using machine.send()?


     const fetchMachine = Machine(
        {
          id: 'test',
          initial: 'init',
          context: {
            id: '',
          },
          states: {
            init: {
              on: {
                LOGIN: 'fetch',
              },
            },
            fetch: {
              on: {
                LOGOUT: 'init',
              },
            },
          }
       })


      const machine = interpret(fetchMachine).start()

How do I pass an ID to the context?

This does NOT do the trick:

      machine.send({ type: 'LOGIN', id })

Solution

  • You have to use the assign action to update the context. I've updated your example to the following:

    import { Machine, assign } from 'xstate';
    
    // Action to assign the context id
    const assignId = assign({
      id: (context, event) => event.id
    });
    
    export const testMachine = Machine(
      {
        id: 'test',
        initial: 'init',
        context: {
          id: '',
        },
        states: {
          init: {
            on: {
              LOGIN: {
                target: 'fetch',
                actions: [
                  assignId
                ]
              }
            },
          },
          fetch: {
            on: {
              LOGOUT: 'init',
            },
          },
        }
      },
      {
        actions: { assignId }
      }
    );
    
    

    Now once you call the following:

    import { testMachine } from './machines';
    
    const testService = interpret(testMachine).start();
    testService.send({type: 'LOGIN', id: 'test' });
    //or testService.send('LOGIN', { id: 'test'});
    
    
    

    the action assignId will assign data from the event to your context