Created
October 12, 2019 05:04
-
-
Save hckhanh/9c2084afff3ec41159566f3f2ab85ca9 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, | |
DoneInvokeEvent, | |
EventObject, | |
Machine, | |
send, | |
sendParent, | |
StateMachine, | |
StateSchema | |
} from "xstate"; | |
import { setToken } from "../apis"; | |
import { login } from "../apis/user"; | |
import { ErrorMessage } from "../models/error"; | |
import { getError } from "../utils/error"; | |
import AuthMachine from "./AuthMachine"; | |
interface LoginSchema extends StateSchema { | |
states: { | |
idle: {}; | |
loading: {}; | |
error: {}; | |
success: {}; | |
}; | |
} | |
interface LoginContext { | |
error: ErrorMessage; | |
} | |
const LoginMachine: StateMachine< | |
LoginContext, | |
LoginSchema, | |
EventObject | |
> = Machine( | |
{ | |
id: "login", | |
initial: "idle", | |
states: { | |
idle: { | |
// exit: "clearError", | |
on: { | |
LOGIN: "loading" | |
} | |
}, | |
loading: { | |
invoke: { | |
id: "loading", | |
src: (context, event) => | |
login(event.credentials).then(response => ({ | |
rememberMe: event.rememberMe, | |
...response.data | |
})), | |
onDone: { target: "success", actions: ["saveToken"] }, | |
onError: { target: "error", actions: "notifyError" } | |
} | |
}, | |
error: { | |
on: { | |
// exit: "clearError", | |
LOGIN: "loading" | |
} | |
}, | |
success: { | |
type: "final", | |
data: { | |
token: (context: LoginContext, event: EventObject) => { | |
console.log(context, event); | |
return event.data.token; | |
} | |
} | |
} | |
} | |
}, | |
{ | |
actions: { | |
saveToken: (context, event) => | |
setToken(event.data.token as string, event.data.rememberMe), | |
notifyError: assign<LoginContext>((context, event) => ({ | |
error: getError(event.data) | |
})), | |
clearError: assign<LoginContext>((context, event) => ({ | |
error: undefined | |
})) | |
} | |
} | |
); | |
export default LoginMachine; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment