Created
October 12, 2019 05:03
-
-
Save hckhanh/b8d23cc62c9d02bfe301eb0886f01482 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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