Skip to content

Instantly share code, notes, and snippets.

@VinSpee
Last active May 14, 2020 16:55
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 VinSpee/27a401aed669bce4286a0d18ee1e7e61 to your computer and use it in GitHub Desktop.
Save VinSpee/27a401aed669bce4286a0d18ee1e7e61 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
const last = (array) => array[array.length - 1];
const addVideoToYourList = (win) => (context, event) => {
return new Promise((res, rej) => {
if (win) {
return res({ data: { win: true } });
}
rej({ errors: ["NotAuthenticated"] });
});
};
const fetchMachine = Machine(
{
id: "authManager",
initial: "idle",
context: {
authenticated: null,
errors: [],
},
states: {
idle: {
on: {
ADD_VIDEO_TO_YOUR_LIST: {
target: "acting.addingVideoToYourList",
},
},
},
acting: {
initial: "idle",
states: {
idle: {},
addingVideoToYourList: {
invoke: {
id: "addVideoToYourList",
src: addVideoToYourList(false),
onDone: {
target: "#authManager.success",
},
onError: {
target: "#authManager.failure",
actions: assign({
errors: (context, event) => event.data.errors,
authenticated: (context, event) =>
!event.data.errors.includes("NotAuthenticated"),
}),
},
},
},
},
},
success: {
type: "final",
},
failure: {
on: {
'': [
{
cond: "needsAuth",
target: "storingAction",
},
],
},
type: "final"
},
storingAction: {
entry: 'storeAction',
type: "final",
},
},
},
{
guards: {
needsAuth: (context, e) => !context.authenticated,
},
actions: {
storeAction: (context, event) => {
console.log('storing…', { context, action: last(event.type.split('.')) })
}
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment