Skip to content

Instantly share code, notes, and snippets.

@joystick
Created April 24, 2021 18:05
Show Gist options
  • Select an option

  • Save joystick/be338f6d4e6a36efde3050d94f818c08 to your computer and use it in GitHub Desktop.

Select an option

Save joystick/be338f6d4e6a36efde3050d94f818c08 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const checkPrerequisites = () => new Promise(resolve => setTimeout(resolve, 2500))
const fetchPaymentDetails = () =>
new Promise(resolve => {
setTimeout(() => {
resolve({
paymentAuthorizationId: 123,
expiresOn: new Date(Date.now() + 15000)
})
}, 2500)
})
const authorizePayment = () => new Promise(resolve => setTimeout(resolve, 1500))
const paymentAuthorizationMachine = Machine({
id: 'paymentAuthorization',
initial: 'checkPrerequisites',
// we will track payment authorization details in the machine's context
context: {
paymentAuthorizationId: null,
expiresOn: null,
// ...more fields
},
states: {
checkPrerequisites: {
invoke: {
id: 'checkPrerequistes',
src: 'checkPrerequisites',
onDone: {
target: 'fetchingPaymentDetails',
},
onError: {
target: 'prerequisitesNotMet',
},
},
},
fetchingPaymentDetails: {
invoke: {
id: 'fetchPaymentDetails',
src: 'fetchPaymentDetails',
onDone: {
target: 'paymentDetailsFetched',
actions: assign((ctx, event) => {
return event.data;
}),
},
onError: {
target: 'paymentDetailsError',
},
},
},
paymentDetailsFetched: {
after: {
AUTHORIZATION_EXPIRES: {
target: 'authorizationExpired',
},
},
on: {
DISMISS: 'authorizationDismissed',
KEYCHAIN_ACCESS_OK: 'authorizingPayment',
KEYCHAIN_ACCESS_KO: 'biometricFactorError',
},
},
authorizingPayment: {
invoke: {
id: 'authorizePayment',
src: 'authorizePayment',
onDone: {
target: 'paymentAuthorized',
},
onError: {
target: 'authorizationError',
},
},
},
paymentAuthorized: { type: 'final' },
authorizationDismissed: { type: 'final' },
paymentDetailsError: { type: 'final' },
prerequisitesNotMet: { type: 'final' },
authorizationExpired: { type: 'final' },
authorizationError: { type: 'final' },
biometricFactorError: { type: 'final' },
},
}, {
services: {
checkPrerequisites,
fetchPaymentDetails,
authorizePayment
},
delays: {
AUTHORIZATION_EXPIRES: (ctx) => {
return Math.max(ctx.expiresOn - new Date(), 0);
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment