| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- import { Dispatch } from "react";
- import { Action } from "./actionTypes";
- import { login as apiLoginRequest } from "../../api";
- export const login = (username: string, password: string) => async (
- dispatch: Dispatch<Action>
- ) => {
- // Loading login state
- dispatch(loginRequest());
- const errors = {
- 400: "Credenciales inválidas",
- };
- try {
- const res = await apiLoginRequest(username, password);
- if (!res.ok) {
- const msg = (errors as any)[res.status];
- dispatch(loginFailure(msg ?? "Request inválida"));
- const text = await res.text();
- console.log("Error en el login", text);
- return;
- }
- const body = await res.json();
- const userToken = body.token;
- dispatch(loginSuccess(username, userToken));
- } catch (e) {
- console.error(e);
- dispatch(loginFailure("Error de conexión"));
- }
- };
- export const loginRequest = (): Action => ({
- type: "LOGIN_REQUEST",
- });
- export const loginSuccess = (username: string, userToken: string): Action => ({
- type: "LOGIN_SUCCESS",
- username,
- userToken,
- });
- export const loginFailure = (code: string): Action => ({
- type: "LOGIN_FAILURE",
- error: code,
- });
- export const failureDismiss = (): Action => ({
- type: "LOGIN_FAILURE_DISMISS",
- });
|