From e5cfef057f81a29a3030eb4d16b465aa7aa5bac8 Mon Sep 17 00:00:00 2001 From: Vinicius Souza Date: Thu, 31 Oct 2024 10:22:59 -0300 Subject: [PATCH] feat: show loading before user data is read from storage --- src/contexts/AuthContext.tsx | 20 ++++++++++++++++---- src/routes/index.tsx | 7 ++++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/contexts/AuthContext.tsx b/src/contexts/AuthContext.tsx index 82bda15..87179c0 100644 --- a/src/contexts/AuthContext.tsx +++ b/src/contexts/AuthContext.tsx @@ -7,6 +7,7 @@ import { storageUserGet, storageUserSave } from '@storage/storageUser'; type AuthContextData = { user: UserDTO; signIn: (email: string, password: string) => Promise; + isLoadingUserStorageData: boolean; }; type AuthContextProviderProps = { @@ -17,6 +18,7 @@ export const AuthContext = createContext({} as AuthContextData) export function AuthContextProvider({ children }: AuthContextProviderProps) { const [user, setUser] = useState({} as UserDTO); + const [isLoadingUserStorageData, setIsLoadingUserStorageData] = useState(true); async function signIn(email: string, password: string) { try { @@ -33,9 +35,15 @@ export function AuthContextProvider({ children }: AuthContextProviderProps) { } async function loadUserData() { - const loggedUser = await storageUserGet(); - if (loggedUser) { - setUser(loggedUser); + try { + const loggedUser = await storageUserGet(); + if (loggedUser) { + setUser(loggedUser); + } + } catch (error) { + throw error; + } finally { + setIsLoadingUserStorageData(false); } } @@ -43,5 +51,9 @@ export function AuthContextProvider({ children }: AuthContextProviderProps) { loadUserData(); }, []); - return {children}; + return ( + + {children} + + ); } diff --git a/src/routes/index.tsx b/src/routes/index.tsx index 29734ac..354b36f 100644 --- a/src/routes/index.tsx +++ b/src/routes/index.tsx @@ -7,14 +7,19 @@ import { AppRoutes } from './app.routes'; import { gluestackUIConfig } from '../../config/gluestack-ui.config'; import { useAuth } from '@hooks/useAuth'; +import { Loading } from '@components/Loading'; export function Routes() { const theme = DefaultTheme; - const { user } = useAuth(); + const { user, isLoadingUserStorageData } = useAuth(); console.debug(user); theme.colors.background = gluestackUIConfig.tokens.colors.gray700; + if (isLoadingUserStorageData) { + return ; + } + return (