[XState] Track Infinite States with with XState Context

心不动则不痛 提交于 2020-01-19 23:40:56

Consider a text input. It would be impossible for anyone to model every value you could possibly put into it, because the number of possible values is infinite. This is an infinite state.

Infinite state can be tracked and utilized by XState machines as "extended state". This extended state is called context. Context is passed to every function that is triggered by the machine: actions, activities, guards, and more.

In this lesson we learn how to set context and update it through assign actions.

 

const { Machine, interpret, assign } = require("xstate");

const inputMachine = Machine(
  {
    id: "inputMachine",
    initial: "input",
    context: {
      value: "Please enter a color"
    },
    states: {
      input: {
        on: {
          CHANGE_VALUE: {
            actions: ["changeInput"]
          }
        }
      }
    }
  },
  {
    actions: {
      changeInput: assign((context, event) => {
        return { value: event.color };
      })
    }
  }
);

const service = interpret(inputMachine)
  .onTransition(state => {
    console.log(state.context); // red
  })
  .start();
service.send({ type: "CHANGE_VALUE", color: "red" });

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!