Skip to content

Instantly share code, notes, and snippets.

@heyMP
Last active December 12, 2021 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heyMP/81f0aff2b9da52f681ecab639326446b to your computer and use it in GitHub Desktop.
Save heyMP/81f0aff2b9da52f681ecab639326446b to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const isNotMin = (context) => context.count > 0;
// Edit your machine(s) here
const counterMachine = Machine({
id: "counter",
initial: "init",
context: {
count: 0,
},
states: {
init: {
on: {
INCREMENT: {
actions: ['increment'],
cond: 'withinThreshold',
},
DECREMENT: {
actions: ['decrement'],
cond: isNotMin
},
'': [
{ target: 'cooldown', cond: 'aboveThreshold' }
]
}
},
cooldown: {
after: {
1000: {
target: "cooldown",
actions: "decrement",
cond: (context) => context.count > 0
}
},
on: {
// only allow decrement in cooldown state
DECREMENT: {
actions: ['decrement'],
cond: isNotMin
},
'': [
{ target: 'init', cond: (context) => context.count === 0 }
]
}
}
},
}, {
// Actions (anything that directly mutates state)
actions: {
increment: assign((context) => ({
count: context.count + 1
})),
decrement: assign((context) => ({
count: context.count - 1
})),
},
// Guards
guards: {
withinThreshold: context => context.count < 10,
aboveThreshold: context => context.count >= 10,
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment