Overview
TheuseAuth hook provides access to the authentication context, including the current user, sign-in/sign-out functions, and loading state. It handles JWT token management, automatic session expiry, and persistent storage using AsyncStorage.
Usage
AuthProvider
Wrap your app withAuthProvider to enable authentication throughout the component tree:
Return Value
The hook returns anAuthContextType object with the following properties:
The currently authenticated user, or
null if not signed in.Async function to authenticate a user with email and password. On success:
- Stores user data and JWT token in AsyncStorage
- Sets the Authorization header in API client
- Schedules automatic sign-out when token expires
- Redirects to
/(main)/dashboard
Async function to sign out the current user:
- Clears user state
- Removes stored credentials from AsyncStorage
- Removes Authorization header from API client
- Cancels scheduled token expiry timeout
- Redirects to
/landing
Indicates whether authentication state is being loaded or an authentication operation is in progress.
Type Definitions
Implementation Details
Token Management
The hook automatically:- Decodes JWT tokens to extract expiration time
- Schedules automatic sign-out when token expires
- Validates tokens with the backend on app load via
/auth/meendpoint - Falls back to local token validation if network request fails
Persistent Storage
User data and tokens are stored in AsyncStorage under the key@ris_gran_chimu_user:
Session Expiry
When a token expires, the app:- Displays an Alert: “Sesión expirada - Tu sesión ha caducado. Se cerrará la sesión.”
- Automatically calls
signOut()when user dismisses the alert - Redirects to the landing page
Error Handling
ThesignIn function handles various error scenarios:
- 401: “Correo o contraseña incorrectos.”
- 404: “Usuario no encontrado.”
- 500: “Error del servidor. Intenta más tarde.”
- Network error: “No se pudo conectar al servidor. Verifica tu conexión a internet.”
- Other errors: “Ocurrió un error inesperado. Intenta nuevamente.”
Requirements
Dependencies
@react-native-async-storage/async-storage- For persistent storageexpo-router- For navigation../services/apiClient- For API communication and token management
