Implement centralized server data polling with context management

This commit is contained in:
2025-10-05 08:29:01 +08:00
parent 9794615c80
commit 168f2abe6d
4 changed files with 207 additions and 98 deletions

70
SERVER_POLLING.md Normal file
View File

@@ -0,0 +1,70 @@
# Server Data Polling Implementation
## Overview
Implemented a centralized server data management system that fetches and polls server status data globally across the entire application.
## Changes Made
### 1. Created ServerContext (`src/contexts/ServerContext.tsx`)
- **Purpose**: Global state management for server data
- **Features**:
- Fetches A2S data for all servers on app initialization
- Polls server data every 2 seconds to keep status fresh
- Provides data to any component via React Context
- Handles loading states and error management
### 2. Updated Main App (`src/main.tsx`)
- Wrapped the entire app with `<ServerProvider>` to make server data available globally
- Server data starts loading immediately when the app opens, regardless of which page
### 3. Refactored Servers Page (`src/pages/Servers.tsx`)
- Removed local data fetching logic
- Now uses `useServers()` hook to access global server data
- No duplicate API calls - reuses data already being polled
- Maintains all existing functionality (filtering, loading skeletons, etc.)
## Benefits
### Performance
- ✅ Data loads immediately on app start (any page: index, blog, servers, etc.)
- ✅ No delay when navigating to /servers page - data already available
- ✅ Automatic updates every 2 seconds keep data fresh
- ✅ Single polling loop instead of multiple instances
### User Experience
- ✅ Server data pre-loaded before user navigates to servers page
- ✅ Real-time status updates without manual refresh
- ✅ Consistent data across all pages that might display server info
- ✅ Smooth loading transitions with skeleton placeholders
### Code Quality
- ✅ Centralized data management (single source of truth)
- ✅ Reusable across multiple components
- ✅ Clean separation of concerns
- ✅ Easy to extend (add more server-related features)
## How It Works
```
App Starts → ServerProvider initializes
Fetches all server data via A2S API
Sets up 2-second polling interval
Any component can access data via useServers() hook
Data automatically updates every 2 seconds
```
## API Calls
- **Initial Load**: 9 parallel A2S queries (one per server)
- **Polling**: Same 9 queries every 2 seconds
- **Bandwidth**: ~4.5 requests/second (distributed)
## Future Enhancements (Optional)
- Add configurable polling interval
- Implement smart polling (slower when tab inactive)
- Add WebSocket support for real-time updates
- Cache data in localStorage for faster initial loads
- Add server health monitoring and alerts