Skip to content

Instantly share code, notes, and snippets.

@vrogueon
Last active February 8, 2022 15:44
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 vrogueon/857df63a9bd91e645a776ee0ef28e8cf to your computer and use it in GitHub Desktop.
Save vrogueon/857df63a9bd91e645a776ee0ef28e8cf to your computer and use it in GitHub Desktop.
state machine
const paymentsStates = {
id: 'payments',
initial: 'inicial',
states: {
inicial: {
on: {
// Aquí se añaden 2 opciones en la transición, en la primera el
// camino exitoso y la occondición, en la segunda el camino al error
TRANSITION:
[
{
target: 'balanceDue',
cond: (context, event) => true // añadir nuestra validación
},
{ target: 'failed' }
]
}
},
balanceDue: {
on: {
TRANSITION: { target: 'pending' }
}
},
pending: {
on: {
TRANSITION: { target: 'creditOwed' }
}
},
creditOwed: {
on: {
SUCCESS: { target: 'paid' },
FAIL: { target: 'failed' }
}
},
paid: {
on: {
TRANSITION: { target: '' }
}
},
failed: {
on: {
TRANSITION: { target: 'pending' }
}
},
},
onDone: ''
}
const ordersMachine = Machine({
id: 'orders',
initial: 'inicial',
context: {
order: {
testValue: 1
}
},
states: {
inicial: {
on: {
TRANSITION: [
{
target: 'open',
cond: context => context.order.testValue == 1
},
{ target: 'cancelled' }
]
}
},
open: {
on: {
TRANSITION: {
target: 'confirmed'
}
},
// Se pueden anidar flujos dentro de las máquinas de estado pasandolos como estados hijos
...paymentsStates
},
confirmed: {
on: {
TRANSITION: {
target: 'complete'
}
}
},
complete: {
on: {
TRANSITION: {
target: 'cancelled'
}
}
},
cancelled: {
type: 'final'
}
},
// Los guards son funciones que sirven de validadores
guards: {
test: (context, event) => context.order.testValue == 1
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment