refactor: enhance category data fetching logic in SharedCarousel and CategoryList components by simplifying cache checks and improving logging for better maintainability

This commit is contained in:
sebseb7
2025-07-23 10:13:41 +02:00
parent a2b7a2509f
commit e472e6bb77
3 changed files with 69 additions and 138 deletions

View File

@@ -15,6 +15,15 @@ import { useParams, useSearchParams } from 'react-router-dom';
import { getAllSettingsWithPrefix } from '../utils/sessionStorage.js';
import { withI18n } from '../i18n/withTranslation.js';
// Check if window.productCache exists and has the categoryTree_209 key
if (typeof window !== 'undefined') {
console.log('Content.js loaded - window.productCache exists:', !!window.productCache);
if (window.productCache) {
console.log('Content.js loaded - window.productCache keys:', Object.keys(window.productCache));
console.log('Content.js loaded - categoryTree_209 exists:', !!window.productCache["categoryTree_209"]);
}
}
const isNew = (neu) => neu && (new Date().getTime() - new Date(neu).getTime() < 30 * 24 * 60 * 60 * 1000);
// @note SwashingtonCP font is now loaded globally via index.css
@@ -310,53 +319,26 @@ class Content extends Component {
fetchCategoryData(categoryId) {
console.log("============= FETCH CATEGORY DATA =============");
console.log(`Fetching category data for ID: ${categoryId}`);
console.log("window.productCache exists:", !!window.productCache);
// Detailed logging of window.productCache
// Simple direct check for the cache
console.log("fetchCategoryData - window.productCache exists:", !!window.productCache);
if (window.productCache) {
console.log("window.productCache keys:", Object.keys(window.productCache));
console.log("window.productCache type:", typeof window.productCache);
console.log("window.productCache is array:", Array.isArray(window.productCache));
// Log categoryTree_209 details
console.log("categoryTree_209 exists:", !!window.productCache["categoryTree_209"]);
console.log("fetchCategoryData - categoryTree_209 exists:", !!window.productCache["categoryTree_209"]);
if (window.productCache["categoryTree_209"]) {
console.log("categoryTree_209 type:", typeof window.productCache["categoryTree_209"]);
console.log("categoryTree_209 keys:", Object.keys(window.productCache["categoryTree_209"]));
console.log("categoryTree exists:", !!window.productCache["categoryTree_209"].categoryTree);
if (window.productCache["categoryTree_209"].categoryTree) {
console.log("categoryTree type:", typeof window.productCache["categoryTree_209"].categoryTree);
console.log("categoryTree is object:", typeof window.productCache["categoryTree_209"].categoryTree === 'object');
console.log("categoryTree sample:", JSON.stringify(window.productCache["categoryTree_209"].categoryTree).substring(0, 100) + "...");
}
console.log("fetchCategoryData - categoryTree_209.categoryTree exists:",
!!window.productCache["categoryTree_209"].categoryTree);
}
} else {
console.log("window.productCache is not defined or null");
}
// IMPORTANT: Check for the exact structure mentioned in the requirement
// window.productCache = {"categoryTree_209":{"categoryTree": ...}}
const hasCache = typeof window.productCache === 'object' &&
window.productCache !== null &&
typeof window.productCache["categoryTree_209"] === 'object' &&
window.productCache["categoryTree_209"] !== null &&
typeof window.productCache["categoryTree_209"].categoryTree === 'object' &&
window.productCache["categoryTree_209"].categoryTree !== null;
console.log("Has valid cache structure:", hasCache);
if (hasCache) {
console.log("✅ Found categoryTree_209.categoryTree in cache");
if (window.productCache &&
window.productCache["categoryTree_209"] &&
window.productCache["categoryTree_209"].categoryTree) {
console.log("Found categoryTree_209.categoryTree in cache");
// Check for specific category data in cache
const cachedData = getCachedCategoryData(categoryId);
console.log("Has cached category data:", !!cachedData);
if (cachedData) {
console.log("Using cached category data for", categoryId);
console.log("Using cached category data for", categoryId);
this.processDataWithCategoryTree(cachedData, categoryId);
return;
} else {
@@ -367,14 +349,13 @@ class Content extends Component {
attributes: [],
categoryName: this.getCategoryNameFromTree(categoryId)
};
console.log("Using category tree data without products");
console.log("Category name from tree:", emptyResponse.categoryName);
console.log("Using category tree data without products");
this.processDataWithCategoryTree(emptyResponse, categoryId);
return;
}
}
console.log("No category tree found in cache, proceeding with socket.io query");
console.log("No category tree found in cache, proceeding with socket.io query");
// Only if we don't have the category tree in cache, proceed with socket.io query
console.log(`Registering for productList:${categoryId}`);

View File

@@ -39,24 +39,12 @@ const getProductCache = () => {
// Initialize categories
const initializeCategories = (language = 'en') => {
const productCache = getProductCache();
if (productCache && productCache[`categoryTree_209_${language}`]) {
const cached = productCache[`categoryTree_209_${language}`];
if (cached.categoryTree) {
return processCategoryTree(cached.categoryTree);
}
}
// Only fallback to old cache format if we're looking for German (default language)
// This prevents showing German categories when user wants English categories
if (language === 'de' && productCache && productCache["categoryTree_209"]) {
const cached = productCache["categoryTree_209"];
if (cached.categoryTree) {
return processCategoryTree(cached.categoryTree);
}
}
// Try language-specific cache first, then fallback to default
const cached = productCache?.[`categoryTree_209_${language}`]?.categoryTree ||
(language === 'de' && productCache?.["categoryTree_209"]?.categoryTree);
return [];
return cached ? processCategoryTree(cached) : [];
};
const SharedCarousel = () => {
@@ -92,46 +80,49 @@ const SharedCarousel = () => {
}, [i18n]);
useEffect(() => {
if (
rootCategories.length === 0 &&
typeof window !== "undefined"
) {
console.log("SharedCarousel: Fetching categories by ignoring",window.productCache);
window.socketManager.emit("categoryList", { categoryId: 209, language: currentLanguage, requestTranslation: true }, (response) => {
if (response && response.success) {
// Use translated data if available, otherwise fall back to original
const categoryTreeToUse = response.translation || response.categoryTree;
if (categoryTreeToUse) {
// Only fetch if we don't have categories
if (rootCategories.length === 0 && typeof window !== "undefined") {
const productCache = getProductCache();
const hasCache = productCache?.[`categoryTree_209_${currentLanguage}`]?.categoryTree ||
(currentLanguage === 'de' && productCache?.["categoryTree_209"]?.categoryTree);
if (!hasCache) {
window.socketManager.emit("categoryList", { categoryId: 209, language: currentLanguage, requestTranslation: true }, (response) => {
if (response && response.success) {
// Use translated data if available, otherwise fall back to original
const categoryTreeToUse = response.translation || response.categoryTree;
if (categoryTreeToUse) {
// Store in cache with language-specific key
try {
if (!window.productCache) window.productCache = {};
window.productCache[`categoryTree_209_${currentLanguage}`] = {
categoryTree: categoryTreeToUse,
timestamp: Date.now(),
};
} catch (err) {
console.error(err);
}
const newCategories = categoryTreeToUse.children || [];
setRootCategories(newCategories);
}
} else if (response && response.categoryTree) {
// Fallback for old response format
// Store in cache with language-specific key
try {
if (!window.productCache) window.productCache = {};
window.productCache[`categoryTree_209_${currentLanguage}`] = {
categoryTree: categoryTreeToUse,
categoryTree: response.categoryTree,
timestamp: Date.now(),
};
} catch (err) {
console.error(err);
}
const newCategories = categoryTreeToUse.children || [];
const newCategories = response.categoryTree.children || [];
setRootCategories(newCategories);
}
} else if (response && response.categoryTree) {
// Fallback for old response format
// Store in cache with language-specific key
try {
if (!window.productCache) window.productCache = {};
window.productCache[`categoryTree_209_${currentLanguage}`] = {
categoryTree: response.categoryTree,
timestamp: Date.now(),
};
} catch (err) {
console.error(err);
}
const newCategories = response.categoryTree.children || [];
setRootCategories(newCategories);
}
});
});
}
}
}, [rootCategories.length, currentLanguage]);

View File

@@ -162,17 +162,11 @@ class CategoryList extends Component {
}
fetchCategories = () => {
if (this.state.fetchedCategories) {
console.log('Categories already fetched, skipping');
return;
}
// Get current language from state
const currentLanguage = this.state.currentLanguage || 'de';
// Initialize global cache object if it doesn't exist
// @note Handle both SSR (global.window) and browser (window) environments
const windowObj = (typeof global !== "undefined" && global.window) ||
(typeof window !== "undefined" && window);
@@ -180,56 +174,21 @@ class CategoryList extends Component {
windowObj.productCache = {};
}
// Check if we have a valid cache in the global object
try {
const cacheKey = `categoryTree_209_${currentLanguage}`;
const cachedData = windowObj && windowObj.productCache ? windowObj.productCache[cacheKey] : null;
if (cachedData) {
const { categoryTree, fetching } = cachedData;
//const cacheAge = Date.now() - timestamp;
//const tenMinutes = 10 * 60 * 1000; // 10 minutes in milliseconds
// If data is currently being fetched, wait for it
if (fetching) {
//console.log('CategoryList: Data is being fetched, waiting...');
const checkInterval = setInterval(() => {
const currentCache = windowObj && windowObj.productCache ? windowObj.productCache[cacheKey] : null;
if (currentCache && !currentCache.fetching) {
clearInterval(checkInterval);
if (currentCache.categoryTree) {
this.processCategoryTree(currentCache.categoryTree);
}
}
}, 100);
return;
}
// If cache is less than 10 minutes old, use it
if (/*cacheAge < tenMinutes &&*/ categoryTree) {
//console.log('Using cached category tree, age:', Math.round(cacheAge/1000), 'seconds');
// Defer processing to next tick to avoid blocking
//setTimeout(() => {
this.processCategoryTree(categoryTree);
//}, 0);
//return;
}
}
} catch (err) {
console.error("Error reading from cache:", err);
}
// Mark as being fetched to prevent concurrent calls
const cacheKey = `categoryTree_209_${currentLanguage}`;
if (windowObj && windowObj.productCache) {
windowObj.productCache[cacheKey] = {
fetching: true,
timestamp: Date.now(),
};
const cachedData = windowObj?.productCache?.[cacheKey];
// Use cache if available
if (cachedData?.categoryTree) {
this.processCategoryTree(cachedData.categoryTree);
return;
}
// Mark as being fetched
if (windowObj?.productCache) {
windowObj.productCache[cacheKey] = { fetching: true, timestamp: Date.now() };
}
this.setState({ fetchedCategories: true });
//console.log('CategoryList: Fetching categories from socket');
console.log("CategoryList: Fetching categories by ignoring",window.productCache);
window.socketManager.emit("categoryList", { categoryId: 209, language: currentLanguage, requestTranslation: true }, (response) => {
if (response && response.success) {
// Use translated data if available, otherwise fall back to original