Skip to content

Instantly share code, notes, and snippets.

@10thfloor
Created March 20, 2023 16:42
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 10thfloor/f446a40b45489c2e9c4104f1052ab3cc to your computer and use it in GitHub Desktop.
Save 10thfloor/f446a40b45489c2e9c4104f1052ab3cc 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 checkoutMachine = Machine(
{
id: 'checkout',
initial: 'cart',
context: {
items: [],
subtotal: 0,
shippingAddress: null,
billingAddress: null,
paymentMethod: null,
orderNumber: null
},
states: {
cart: {
on: {
ADD_TO_CART: {
actions: assign({
items: (context, event) => [...context.items, event.item]
})
},
CHECKOUT: 'checkoutForm'
}
},
checkoutForm: {
initial: 'shipping',
states: {
shipping: {
entry: assign({
shippingAddress: (context, event) => {
if (!context.shippingAddress) {
// fetch data here
return null;
}
return context.shippingAddress;
}
}),
on: {
NEXT: 'billing',
PREVIOUS: undefined,
SET_SHIPPING_ADDRESS: {
actions: assign({
shippingAddress: (_, event) => event.address
})
},
UPDATE_SHIPPING_ADDRESS: {
actions: assign({
shippingAddress: (_, event) => {
// send updated shipping address to backend and fetch updated data
return null;
}
})
}
}
},
billing: {
entry: assign({
billingAddress: (context, event) => {
if (!context.billingAddress) {
// fetch data here
return null;
}
return context.billingAddress;
}
}),
on: {
NEXT: 'payment',
PREVIOUS: 'shipping',
SET_BILLING_ADDRESS: {
actions: assign({
billingAddress: (_, event) => event.address
})
},
UPDATE_BILLING_ADDRESS: {
actions: assign({
billingAddress: (_, event) => {
// send updated billing address to backend and fetch updated data
return null;
}
})
}
}
},
payment: {
entry: assign({
paymentMethod: (context, event) => {
if (!context.paymentMethod) {
// fetch data here
return null;
}
return context.paymentMethod;
}
}),
on: {
NEXT: 'review',
PREVIOUS: 'billing',
SET_PAYMENT_METHOD: {
actions: assign({
paymentMethod: (_, event) => event.paymentMethod
})
},
UPDATE_PAYMENT_METHOD: {
actions: assign({
paymentMethod: (_, event) => {
// send updated payment method to backend and fetch updated data
return null;
}
})
}
}
},
review: {
on: {
PLACE_ORDER: 'success',
PREVIOUS: 'payment'
}
},
success: {
type: 'final'
}
}
}
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment