refactor: standardize socket communication by replacing socket prop usage with window.socketManager across multiple components for improved consistency and maintainability

This commit is contained in:
sebseb7
2025-07-23 08:21:30 +02:00
parent 4e6b63a6a4
commit 61faf654bc
10 changed files with 52 additions and 148 deletions

View File

@@ -108,21 +108,6 @@ class AdminPage extends React.Component {
window.addEventListener('storage', this.handleStorageChange);
}
componentDidUpdate(prevProps) {
// Handle socket connection changes
const wasConnected = prevProps.socket && prevProps.socket.connected;
const isNowConnected = this.props.socket && this.props.socket.connected;
if (!wasConnected && isNowConnected) {
// Socket just connected, add listeners and reload data
this.addSocketListeners();
this.loadInitialData();
} else if (wasConnected && !isNowConnected) {
// Socket just disconnected, remove listeners
this.removeSocketListeners();
}
}
componentWillUnmount() {
this.removeSocketListeners();
// Clear interval and remove event listeners
@@ -133,12 +118,11 @@ class AdminPage extends React.Component {
}
loadInitialData = () => {
if (this.props.socket && this.props.socket.connected) {
this.props.socket.emit('getStats', (stats) => {
window.socketManager.emit('getStats', (stats) => {
console.log('AdminPage: getStats', JSON.stringify(stats,null,2));
this.setState({stats: stats});
});
this.props.socket.emit('initialCarts', (carts) => {
window.socketManager.emit('initialCarts', (carts) => {
console.log('AdminPage: initialCarts', carts);
if(carts && carts.success == true)
{
@@ -153,21 +137,19 @@ class AdminPage extends React.Component {
this.setState({ users: users });
}
});
}
}
addSocketListeners = () => {
if (this.props.socket && this.props.socket.connected) {
// Remove existing listeners first to avoid duplicates
this.removeSocketListeners();
this.props.socket.on('cartUpdated', this.handleCartUpdated);
}
window.socketManager.on('cartUpdated', this.handleCartUpdated);
}
removeSocketListeners = () => {
if (this.props.socket) {
this.props.socket.off('cartUpdated', this.handleCartUpdated);
}
window.socketManager.off('cartUpdated', this.handleCartUpdated);
}
formatPrice = (price) => {

View File

@@ -143,19 +143,15 @@ class GrowTentKonfigurator extends Component {
return;
}
//if (!this.props.socket || !this.props.socket.connected) {
// console.log("Socket not connected yet, waiting for connection to fetch category data");
// return;
//}
console.log(`productList:${categoryId}`);
this.props.socket.off(`productList:${categoryId}`);
window.socketManager.off(`productList:${categoryId}`);
this.props.socket.on(`productList:${categoryId}`,(response) => {
window.socketManager.on(`productList:${categoryId}`,(response) => {
console.log("getCategoryProducts full response", response);
setCachedCategoryData(categoryId, response);
});
this.props.socket.emit("getCategoryProducts", { categoryId: categoryId },
window.socketManager.emit("getCategoryProducts", { categoryId: categoryId },
(response) => {
console.log("getCategoryProducts stub response", response);
}

View File

@@ -13,7 +13,7 @@ import {
} from '@mui/material';
import LockResetIcon from '@mui/icons-material/LockReset';
const ResetPassword = ({ socket }) => {
const ResetPassword = () => {
const navigate = useNavigate();
const location = useLocation();
const { t } = useTranslation();
@@ -59,7 +59,7 @@ const ResetPassword = ({ socket }) => {
setError('');
// Emit verifyResetToken event
socket.emit('verifyResetToken', {
window.socketManager.emit('verifyResetToken', {
token: token,
newPassword: newPassword
}, (response) => {

View File

@@ -104,8 +104,8 @@ class ServerLogsPage extends React.Component {
}
loadHistoricalLogs = () => {
if (this.props.socket && this.props.socket.connected) {
this.props.socket.emit('getLog', (response) => {
window.socketManager.emit('getLog', (response) => {
if (response.success) {
console.log('Last 50 historical logs:', response.data.lines);
const historicalLogs = (response.data.lines || [])
@@ -121,7 +121,6 @@ class ServerLogsPage extends React.Component {
this.setState({ historicalLogsLoaded: true }); // Mark as attempted even if failed
}
});
}
}
componentDidMount() {
@@ -134,23 +133,6 @@ class ServerLogsPage extends React.Component {
window.addEventListener('storage', this.handleStorageChange);
}
componentDidUpdate(prevProps) {
// Handle socket connection changes
const wasConnected = prevProps.socket && prevProps.socket.connected;
const isNowConnected = this.props.socket && this.props.socket.connected;
if (!wasConnected && isNowConnected) {
// Socket just connected, add listeners and reload data
this.addSocketListeners();
if (!this.state.historicalLogsLoaded) {
this.loadHistoricalLogs();
}
} else if (wasConnected && !isNowConnected) {
// Socket just disconnected, remove listeners
this.removeSocketListeners();
}
}
componentWillUnmount() {
this.removeSocketListeners();
// Clear interval and remove event listeners
@@ -161,17 +143,13 @@ class ServerLogsPage extends React.Component {
}
addSocketListeners = () => {
if (this.props.socket && this.props.socket.connected) {
// Remove existing listeners first to avoid duplicates
this.removeSocketListeners();
this.props.socket.on('log', this.handleLogEntry);
}
// Remove existing listeners first to avoid duplicates
this.removeSocketListeners();
window.socketManager.on('log', this.handleLogEntry);
}
removeSocketListeners = () => {
if (this.props.socket) {
this.props.socket.off('log', this.handleLogEntry);
}
window.socketManager.off('log', this.handleLogEntry);
}
formatLogLevel = (level) => {

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect, useContext } from 'react';
import React, { useState, useEffect } from 'react';
import Typography from '@mui/material/Typography';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
@@ -7,7 +7,6 @@ import Box from '@mui/material/Box';
import CircularProgress from '@mui/material/CircularProgress';
import { Link as RouterLink } from 'react-router-dom';
import LegalPage from './LegalPage.js';
import SocketContext from '../contexts/SocketContext.js';
// Helper function to recursively collect all categories from the tree
const collectAllCategories = (categoryNode, categories = [], level = 0) => {
@@ -68,7 +67,6 @@ const Sitemap = () => {
const initialCategories = initializeCategories();
const [categories, setCategories] = useState(initialCategories);
const [loading, setLoading] = useState(initialCategories.length === 0);
const context = useContext(SocketContext);
const sitemapLinks = [
@@ -105,8 +103,8 @@ const Sitemap = () => {
}
// Otherwise, fetch from socket if available (only in browser)
if (context && context.socket && context.socket.connected && typeof window !== "undefined") {
context.socket.emit('categoryList', { categoryId: 209, language: 'en', requestTranslation: true }, (response) => {
if (typeof window !== "undefined") {
window.socketManager.emit('categoryList', { categoryId: 209, language: 'en', requestTranslation: true }, (response) => {
if (response && response.categoryTree) {
// Store in cache
try {
@@ -133,7 +131,7 @@ const Sitemap = () => {
};
fetchCategories();
}, [context, categories.length]);
}, [categories.length]);
const content = (
<>

View File

@@ -91,17 +91,6 @@ class UsersPage extends React.Component {
window.addEventListener('storage', this.handleStorageChange);
}
componentDidUpdate(prevProps) {
// Handle socket connection changes
const wasConnected = prevProps.socket && prevProps.socket.connected;
const isNowConnected = this.props.socket && this.props.socket.connected;
if (!wasConnected && isNowConnected) {
// Socket just connected, reload data
this.loadInitialData();
}
}
componentWillUnmount() {
// Clear interval and remove event listeners
if (this.checkLoginInterval) {
@@ -111,8 +100,8 @@ class UsersPage extends React.Component {
}
loadInitialData = () => {
if (this.props.socket && this.props.socket.connected) {
this.props.socket.emit('getUsers', (response) => {
window.socketManager.emit('getUsers', (response) => {
if (response.success) {
console.log('Users:', response.data.users);
console.log('Total count:', response.data.totalCount);
@@ -126,7 +115,7 @@ class UsersPage extends React.Component {
console.error('Error:', response.error);
}
});
}
}
formatDate = (dateString) => {
@@ -190,14 +179,9 @@ class UsersPage extends React.Component {
}
handleSwitchUser = (email) => {
if (!this.props.socket || !this.props.socket.connected) {
this.showNotification('Socket not connected', 'error');
return;
}
this.setState({ switchingUser: true });
this.props.socket.emit('switchUser', { email }, (response) => {
window.socketManager.emit('switchUser', { email }, (response) => {
console.log('Switch user response:', response);
this.setState({ switchingUser: false });
@@ -225,14 +209,10 @@ class UsersPage extends React.Component {
}
handleSwitchBackToAdmin = () => {
if (!this.props.socket || !this.props.socket.connected) {
this.showNotification('Socket not connected', 'error');
return;
}
this.setState({ switchingUser: true });
this.props.socket.emit('switchBackToAdmin', (response) => {
window.socketManager.emit('switchBackToAdmin', (response) => {
console.log('Switch back to admin response:', response);
this.setState({ switchingUser: false });