Search code examples
statestate-managementxstate

Where is the action creator message stored in Xstate?


Excerpt from the assign action docs:

import { Machine, assign } from 'xstate';
// example: property assigner

// ...
  actions: assign({
    // increment the current count by the event value
    count: (context, event) => context.count + event.value,

    // assign static value to the message (no function needed)
    message: 'Count changed'
  }),
// ...

Where is "Count changed" stored? In the context?


Solution

  • Yes correct!

    Here is a demo in codesandbox to demonstrate it, and a breakdown of it:

    I created a machine around the assign action that better demonstrates what will happen:

    const testMachine = Machine(
      {
        id: "testMachine",
        initial: "lightOn",
        context: {
          count: 0,
          message: ""
        },
        states: {
          lightOn: {
            on: {
              SWITCH_OFF: {
                target: "lightOff",
                actions: assign({
                  // increment the current count by the event value
                  count: (context, event) => context.count + event.value,
                  // assign static value to the message (no function needed)
                  message: "Count changed"
                })
              }
            }
          },
          lightOff: {
            on: {
              SWITCH_ON: "lightOn"
            }
          }
        }
      }
    );
    

    Using the machine in react would look like this:

    import * as React from "react";
    import { useMachine } from "@xstate/react";
    import { testMachine } from "./machines";
    
    export default function Test() {
      const [current, send] = useMachine(testMachine);
      return <>
        <div>Message:{current.context.message}</div>
        <div>Count:{current.context.count}</div>
        <button onClick={() => send('SWITCH_OFF', { value: 1 })}>Transition</button>
      </>
    }
    

    The initial component rendered will be:

    enter image description here

    And on clicking the "Transition" button, the event SWITCH_OFF will be sent to the machine, resulting in the action triggering, and the count incrementing in the context, and the message being assigned.

    Resulting in the component rendering the following:

    enter image description here