reducer.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { Reducer } from "react";
  2. import { Action } from "./actionTypes";
  3. import keys from "../storageKeys";
  4. export const defaultState = {
  5. loggingIn: false,
  6. loggedIn: false,
  7. userToken: null,
  8. username: null,
  9. };
  10. // Estado inicial de usuario
  11. export const getInitialState = (): State => {
  12. const userToken = localStorage.getItem(keys.userToken);
  13. const username = localStorage.getItem(keys.username);
  14. return { ...defaultState, username, userToken, loggedIn: !!userToken };
  15. };
  16. export type State = {
  17. loggingIn?: Boolean | null;
  18. loggedIn?: Boolean | null;
  19. userToken?: string | null;
  20. username?: string | null;
  21. error?: string | null;
  22. };
  23. const reducer: Reducer<State, Action> = (state, action) => {
  24. switch (action.type) {
  25. case "LOGIN_REQUEST":
  26. return {
  27. ...state,
  28. loggingIn: true,
  29. loggedIn: false,
  30. username: action.username,
  31. };
  32. case "LOGIN_SUCCESS":
  33. return {
  34. loggedIn: true,
  35. loggingIn: false,
  36. username: action.username,
  37. userToken: action.userToken,
  38. };
  39. case "LOGIN_FAILURE_DISMISS":
  40. return {
  41. ...state,
  42. error: undefined,
  43. };
  44. case "LOGIN_FAILURE":
  45. return {
  46. error: action.error,
  47. };
  48. case "LOGOUT":
  49. return {};
  50. default:
  51. return state;
  52. }
  53. };
  54. export default reducer;