Jelajahi Sumber

Persistir user token

wilitp 4 tahun lalu
induk
melakukan
1338ff612d

+ 2 - 2
app/src/context/auth/AuthProvider.tsx

@@ -1,9 +1,9 @@
 import React, { createContext, useReducer, Dispatch, FC } from "react";
 import React, { createContext, useReducer, Dispatch, FC } from "react";
-import reducer, { State } from "./reducer";
+import reducer, { State, getInitialState } from "./reducer";
 import { Action } from "./actionTypes";
 import { Action } from "./actionTypes";
 
 
 const UserProvider: FC = ({ children }) => {
 const UserProvider: FC = ({ children }) => {
-  const [state, dispatch] = useReducer(reducer, {});
+  const [state, dispatch] = useReducer(reducer, getInitialState());
 
 
   return (
   return (
     <UserStateContext.Provider value={state}>
     <UserStateContext.Provider value={state}>

+ 2 - 0
app/src/context/auth/actions.ts

@@ -1,6 +1,7 @@
 import { Dispatch } from "react";
 import { Dispatch } from "react";
 import { Action } from "./actionTypes";
 import { Action } from "./actionTypes";
 import { login as apiLoginRequest } from "../../api";
 import { login as apiLoginRequest } from "../../api";
+import keys from "../storageKeys";
 
 
 // Accion asincrona: Loguea al usuario
 // Accion asincrona: Loguea al usuario
 export const login = (username: string, password: string) => async (
 export const login = (username: string, password: string) => async (
@@ -25,6 +26,7 @@ export const login = (username: string, password: string) => async (
     const body = await res.json();
     const body = await res.json();
 
 
     const userToken = body.token;
     const userToken = body.token;
+    localStorage.setItem(keys.userToken, userToken);
 
 
     dispatch(loginSuccess(username, userToken));
     dispatch(loginSuccess(username, userToken));
   } catch (e) {
   } catch (e) {

+ 13 - 6
app/src/context/auth/reducer.ts

@@ -1,5 +1,6 @@
 import { Reducer } from "react";
 import { Reducer } from "react";
-import { Action, ActionType } from "./actionTypes";
+import { Action } from "./actionTypes";
+import keys from "../storageKeys";
 
 
 export const defaultState = {
 export const defaultState = {
   loggingIn: false,
   loggingIn: false,
@@ -8,12 +9,18 @@ export const defaultState = {
   username: null,
   username: null,
 };
 };
 
 
+// Estado inicial de usuario
+export const getInitialState = (): State => {
+  const userToken = localStorage.getItem(keys.userToken);
+  return { ...defaultState, userToken, loggedIn: !!userToken };
+};
+
 export type State = {
 export type State = {
-  loggingIn?: Boolean;
-  loggedIn?: Boolean;
-  userToken?: string;
-  username?: string;
-  error?: string;
+  loggingIn?: Boolean | null;
+  loggedIn?: Boolean | null;
+  userToken?: string | null;
+  username?: string | null;
+  error?: string | null;
 };
 };
 
 
 const reducer: Reducer<State, Action> = (state, action) => {
 const reducer: Reducer<State, Action> = (state, action) => {