-
-
Save vrogueon/857df63a9bd91e645a776ee0ef28e8cf to your computer and use it in GitHub Desktop.
state machine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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