Created
January 23, 2020 14:17
-
-
Save christianalfoni/265f6a7f30c102d69cd5cd70c79aded4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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