Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active April 29, 2022 06:52
Show Gist options
  • Save ryanflorence/864336487bf3ad135ac0a1fc5593b03b to your computer and use it in GitHub Desktop.
Save ryanflorence/864336487bf3ad135ac0a1fc5593b03b to your computer and use it in GitHub Desktop.
enum State {
Idle,
LoadingJwt,
Success,
Error,
}
type Data = { error?: string; jwt?: string };
function Comp() {
let [state, setState] = useState<State>(State.Idle);
let [data, setData] = useState<Data>({});
let transition = async () => {
switch (state) {
case State.LoadingJwt: {
try {
let jwt = await getJwtFromProvider();
setData({ ...data, jwt });
setState(State.Success);
} catch (error) {
setData({ ...data, error: error.message });
setState(State.Error);
}
break;
}
case State.Error: {
setTimeout(() => {
setState(State.Idle);
}, 2000);
break;
}
case State.Success: {
await createSession(data.jwt);
navigate("/dashboard");
}
}
};
useEffect(() => {
transition();
}, [state]);
return <div>{/* ... */}</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment