Skip to content

Instantly share code, notes, and snippets.

@hckhanh
Created October 12, 2019 05:03
Show Gist options
  • Save hckhanh/b8d23cc62c9d02bfe301eb0886f01482 to your computer and use it in GitHub Desktop.
Save hckhanh/b8d23cc62c9d02bfe301eb0886f01482 to your computer and use it in GitHub Desktop.
import {
assign,
EventObject,
Machine,
send,
StateMachine,
StateSchema
} from "xstate";
import { getToken } from "../apis";
import LoginMachine from "./LoginMachine";
interface AuthSchema extends StateSchema {
states: {
unauthorized: {};
authorized: {};
};
}
interface AuthContext {
token: string | null;
}
const AuthMachine: StateMachine<AuthContext, AuthSchema, EventObject> = Machine(
{
id: "auth",
context: { token: getToken() },
initial: "unauthorized",
states: {
unauthorized: {
invoke: {
id: "login",
src: LoginMachine,
onDone: "authorized"
}
},
authorized: {
on: {
LOGOUT: "unauthorized"
}
}
}
},
{
actions: {
updateToken: assign<AuthContext>((context, event) => ({
token: event.data.token
})),
checkToken: (context, event) => {
console.log(context, event, AuthMachine);
if (context.token) {
send("TOKEN_VALID", { id: "authorized" });
}
}
}
}
);
export default AuthMachine;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment