Context

Context

is a place for storing data

Data in context can be:

  • initial

  • assigned by an action

How to define context in machine?

const machine = Machine({
  context: {
    foo: 10,
    bar: 50
  },
  states: {}
});

// or

const createMachine = (foo,bar) => Machine({
  context: {
    foo,
    bar
  },
  states: {}
});

const machine = createMachine(10, 50)

Assigning new context's value  

const countMachine = Machine({
  context: {
    count: 0,
  },
  states: {
    ready: {
      on: {
        INCREMENT: {
          actions: assign({
            count: (context) => context.count + 1
          })
        }
      }
    }
  }
});

assign is special action from XState used to update the machine's context

Assign gets current context and event as a params

on: {
  INCREMENT: {
    actions: assign({
      // context will be an object with current value of `count: 0`
      // event will be an object of type matching `INCREMENT`
      count: (context, event) => context.count + 1
    })
  }
}

coding time!

Made with Slides.com