Skip to content

Instantly share code, notes, and snippets.

@2WheelCoder

2WheelCoder/machine.js

Last active May 28, 2020
Embed
What would you like to do?
Generated by XState Viz: https://xstate.js.org/viz
const getCheckout = () => Promise.reject({
message: 'There was an error creating your order.',
errors: [{
message: "Zip is not valid for Canada",
code: "INVALID_FOR_COUNTRY",
field:["input","shippingAddress","zip"]
}],
})
const getShippingRates = () => {}
const setShippingRate = () => {}
const isPickup = () => {}
const checkoutMachine = Machine(
{
id: 'checkout',
initial: 'acceptingUserInfo',
context: {
customerInfo: null,
checkoutId: null,
webUrl: null,
deliveryMethod: null,
client: null,
shippingRates: undefined,
selectedShippingRate: null,
errors: []
},
states: {
acceptingUserInfo: {
on: {
SUBMIT_INFO: {
target: 'creatingCheckout',
actions: ['updateCustomerInfo'],
},
},
},
creatingCheckout: {
invoke: {
id: 'getCheckout',
src: getCheckout,
onDone: {
target: 'loadingShippingRates',
actions: ['updateCheckout'],
},
onError: {
target: 'failure',
actions: ['updateErrors']
}
},
},
loadingShippingRates: {
invoke: {
id: 'getShippingRates',
src: getShippingRates,
onDone: [
{
target: 'settingShippingRate',
actions: ['updateShippingRates', 'selectPickupRate'],
cond: isPickup,
},
{
target: 'acceptingShippingRate',
actions: ['updateShippingRates'],
},
],
onError: 'waitingToRetryShippingRates',
},
},
waitingToRetryShippingRates: {
after: {
1000: 'loadingShippingRates',
},
},
acceptingShippingRate: {
on: {
SELECT: {
target: 'settingShippingRate',
actions: ['updateSelectedShippingRate'],
},
},
},
settingShippingRate: {
invoke: {
id: 'setShippingRate',
src: setShippingRate,
onDone: 'checkoutComplete',
onError: 'failure',
},
},
checkoutComplete: {
type: 'final',
},
failure: {
on: {
SUBMIT_INFO: {
target: 'creatingCheckout',
actions: ['updateCustomerInfo'],
},
},
},
},
},
{
actions: {
updateCustomerInfo: assign({
customerInfo: (context, event) => event.customerInfo,
}),
updateCheckout: assign({
webUrl: (context, event) => event.data.webUrl,
checkoutId: (context, event) => event.data.id,
}),
updateShippingRates: assign({
shippingRates: (context, event) => event.data,
}),
updateSelectedShippingRate: assign({
selectedShippingRate: (context, event) => event.shippingRate,
}),
selectPickupRate: assign({
selectedShippingRate: (context, event) =>
event.data.filter(
shippingRate => shippingRate.title === 'Pick Up In-Store'
)[0],
}),
updateErrors: assign({
errors: (context, event) => [
...context.errors,
event.data.errors
]
})
},
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.