Skip to content

Instantly share code, notes, and snippets.

@christianalfoni
Created January 23, 2020 14:17
Show Gist options
  • Save christianalfoni/265f6a7f30c102d69cd5cd70c79aded4 to your computer and use it in GitHub Desktop.
Save christianalfoni/265f6a7f30c102d69cd5cd70c79aded4 to your computer and use it in GitHub Desktop.
// I have a couple of transition states, "authenticated", "authenticating", "unauthenticated"
const machine = new Machine({
initial: 'unauthenticated',
states: {
unauthenticated: 'authenticating',
authenticating: ['authenticated', 'unauthenticated'],
authenticated: 'unauthenticated'
}
})
// I have a couple of state values (context) related to these
// two states
const auth = {
state: machine,
user: null,
error: null
}
// I have logic transitioing my machine safely, though
// the logic related to it can basically do whatever it wants
// unrelated to the machine
async function login() {
if (auth.state.machine.transition('authenticating')) {
try {
const user = await fetch('/user')
if (auth.state.machine.transition('authenticated')) {
auth.user = user
}
} catch (error) {
if (auth.state.machine.transition('authenticated')) {
auth.error = error
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment