State Management
Server State (TanStack Query)
We refer to "Server State" as any data that comes from the API (User profile, List of cameras, Alerts). We use TanStack Query (React Query) to manage this because:
- Deduplication: Multiple components can request
useUser()without spamming the API. - Caching: Instant navigation between pages.
- Invalidation: When we mutate data (e.g.,
updateCameraName), we simply callqueryClient.invalidateQueries(['cameras'])to refresh the UI automatically.
Global Client State (Context)
AuthProvider
Wraps the entire application.
- Responsibility: Checks for a valid JWT in storage on mount.
- Handling 401s: If the API returns 401, it automatically redirects to
/loginand wipes the session.
ThemeProvider
Manages Light/Dark mode preference (persisted in LocalStorage).
Authentication Flow
- Login:
api.post('/login')returns{ token, refreshToken }. - Storage: We use
TokenManager(singleton) to store the token in HTTP-only cookies (for security) or LocalStorage (for ease of access). - Requests: The custom
fetchwrapper (or Axios interceptor) injectsAuthorization: Bearer <token>into every request. - Sockets:
useSocketManageralso independently reads the token to authenticate websockets.