Skip to content

Instantly share code, notes, and snippets.

@w33ble
Created April 15, 2020 18:35
Show Gist options
  • Save w33ble/5ac54ac412d83ffc610aee971aec3a52 to your computer and use it in GitHub Desktop.
Save w33ble/5ac54ac412d83ffc610aee971aec3a52 to your computer and use it in GitHub Desktop.
messing with xstate
const { Machine, assign, interpret } = require('xstate');
const glassMachine = Machine(
{
id: 'glass',
// the initial context (extended state) of the statechart
context: {
amount: 0,
},
initial: 'empty',
states: {
empty: {
on: {
FILL: {
target: 'filling',
actions: 'addWater',
},
},
},
filling: {
on: {
// Transient transition
'': {
target: 'full',
cond: 'glassIsFull',
},
FILL: {
target: 'filling',
actions: 'addWater',
},
},
},
full: {
type: 'final',
// on: {
// FILL: {
// target: 'filling',
// actions: 'addWater',
// cond: 'glassIsNotFull',
// },
// },
},
},
},
{
actions: {
addWater: assign((context, event) => {
// console.log('adding water');
return {
amount: context.amount + 1,
};
}),
},
guards: {
glassIsFull(context, event) {
return context.amount >= 10;
},
glassIsNotFull(context, event) {
return context.amount < 10;
},
},
},
);
// const glassService = interpret(glassMachine).onTransition((state) =>
// console.log(state.value, state.context),
// );
const glassService = interpret(glassMachine);
glassService.start();
for (let i = 0; i < 15; i += 1) {
const nextState = glassService.send('FILL');
if (i === 0) console.log(nextState);
if (!nextState.changed) console.log('NOTHING HAPPENED', nextState);
console.log('context', nextState.value, nextState.context, nextState.done);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment