Skip to content

Instantly share code, notes, and snippets.

@bwaidelich
Created May 14, 2021 08:17
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 bwaidelich/a3332373bf62b513ec994ef256f0baec to your computer and use it in GitHub Desktop.
Save bwaidelich/a3332373bf62b513ec994ef256f0baec to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const machine = Machine(
{
id: "buyBook",
initial: "outside",
context: {
loggedIn: false,
subscription: null,
bookId: null,
initialLocation: null,
alreadySubscribedChosen: false
},
states: {
outside: {
on: {
CHOOSE_BOOK: [
{
target: "paywall"
}
]
}
},
outside_authenticated: {
on: {
CHOOSE_BOOK: [
{
target: "bookView",
actions: assign({
bookId: (c, e) => e.bookId
})
}
]
}
},
bookView: {
on: {
CLOSE: {
target: "outside_authenticated",
actions: "redirectToInitial"
}
}
},
paywall: {
on: {
SUBSCRIBE: {
target: "authenticating"
},
ALREADY_SUBSCRIBED: {
target: "authenticating",
actions: assign({
alreadySubscribedChosen: () => true
})
},
CLOSE: {
target: "outside",
actions: "redirectToInitial"
}
}
},
authenticating: {
invoke: {
id: "authenticateUser",
src: "authenticateUser",
onDone: [{
target: "outside_authenticated",
cond: "subscribed",
},
{
target: "noSubscription",
cond: "alreadySubscribedChosen",
},
{
target: "paying"
}
],
onError: {
target: "paymentFailure"
}
}
},
authenticationFailure: {
on: {
RETRY: {
target: "authenticating"
}
}
},
noSubscription: {
on: {
SUBSCRIBE: "paying",
CLOSE: {
target: "outside_authenticated",
actions: "redirectToInitial"
}
}
},
paying: {
always: [
{
target: "bookView",
cond: "subscribed"
}
],
invoke: {
id: "pay",
src: "pay",
onDone: {
target: "paymentSuccess",
actions: assign({
subscription: () => "default"
})
},
onError: {
target: "paymentFailure"
}
}
},
paymentSuccess: {
on: {
OK: {
target: "bookView"
}
}
},
paymentFailure: {
on: {
RETRY: {
target: "paying"
}
}
}
}
},
{
guards: {
loggedIn: (c, e) => c.loggedIn,
subscribed: (c, e) => Boolean(c.subscription),
notSubscribed: (c, e) => !Boolean(c.subscription),
alreadySubscribedChosen: (c, e) => c.alreadySubscribedChosen
},
services: {
authenticateUser: (context, event) =>
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(true);
}, 1000);
}),
pay: (context, event) =>
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(true);
}, 1000);
})
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment