Skip to content

Instantly share code, notes, and snippets.

@lbineau
Last active November 17, 2020 14:51
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 lbineau/9108f855dd47edb4b07b1463bf72e61c to your computer and use it in GitHub Desktop.
Save lbineau/9108f855dd47edb4b07b1463bf72e61c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Service mocks (you can change it)
function obtainTokenService() {
return new Promise(async (resolve, reject) => {
//reject('oops');
resolve('tokenId');
});
}
const onErrorHandler = {
target: "error",
actions: assign({
error: (_, event) => event.data,
}),
};
const INITIAL_CONTEXT = {
token: null,
error: null
}
const paymentMachine = Machine({
id: "BrainTreePaymentMachine",
initial: "idle",
context: INITIAL_CONTEXT,
states: {
idle: {
on: {
START: {
target: "obtainToken",
actions: "initialize"
}
}
},
obtainToken: {
invoke: {
id: 'obtainTokenService',
src: obtainTokenService,
onDone: {
target: "renderHostedFields",
actions: assign({
token: (_, event) => event.data
})
},
onError: onErrorHandler
}
},
renderHostedFields: {
invoke: {
src: 'createCreditCardInstances',
onDone: {
target: "userFillCCForm"
},
onError: onErrorHandler
}
},
userFillCCForm: {
entry: ['displayForm', 'addOnBlur', 'addOnFocus'],
exit: ['removeOnBlur', 'removeOnFocus'],
on: {
SUBMIT: [
{
target: "confirmCardPayment",
// if valid goes to this, invalid otherwise
cond: () => true
},
{ target: '.invalid' }
]
},
initial: 'normal',
states: {
normal: {},
invalid: {}
}
},
confirmCardPayment: {
invoke: {
id: 'confirmCardPayment',
src: () => Promise.all("setPaymentMethodOnCartService", "placeOrderService"),
onDone: {
target: "paymentSuccess"
},
onError: onErrorHandler
},
exit: 'createOrderIdCookie'
},
error: {
entry: 'showModal',
exit: 'discardModal',
on: {
RESET: {
target: "idle",
actions: assign({
error: () => null
})
}
}
},
paymentSuccess: {
entry: 'goToConfirmationPage',
type: "final"
}
}
}, {
actions: {},
guards: {}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment