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:
@@ -15,6 +15,15 @@ import { useParams, useSearchParams } from 'react-router-dom';
|
|||||||
import { getAllSettingsWithPrefix } from '../utils/sessionStorage.js';
|
import { getAllSettingsWithPrefix } from '../utils/sessionStorage.js';
|
||||||
import { withI18n } from '../i18n/withTranslation.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);
|
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
|
// @note SwashingtonCP font is now loaded globally via index.css
|
||||||
@@ -310,53 +319,26 @@ class Content extends Component {
|
|||||||
|
|
||||||
|
|
||||||
fetchCategoryData(categoryId) {
|
fetchCategoryData(categoryId) {
|
||||||
console.log("============= FETCH CATEGORY DATA =============");
|
// Simple direct check for the cache
|
||||||
console.log(`Fetching category data for ID: ${categoryId}`);
|
console.log("fetchCategoryData - window.productCache exists:", !!window.productCache);
|
||||||
console.log("window.productCache exists:", !!window.productCache);
|
|
||||||
|
|
||||||
// Detailed logging of window.productCache
|
|
||||||
if (window.productCache) {
|
if (window.productCache) {
|
||||||
console.log("window.productCache keys:", Object.keys(window.productCache));
|
console.log("fetchCategoryData - categoryTree_209 exists:", !!window.productCache["categoryTree_209"]);
|
||||||
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"]);
|
|
||||||
if (window.productCache["categoryTree_209"]) {
|
if (window.productCache["categoryTree_209"]) {
|
||||||
console.log("categoryTree_209 type:", typeof window.productCache["categoryTree_209"]);
|
console.log("fetchCategoryData - categoryTree_209.categoryTree exists:",
|
||||||
console.log("categoryTree_209 keys:", Object.keys(window.productCache["categoryTree_209"]));
|
!!window.productCache["categoryTree_209"].categoryTree);
|
||||||
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) + "...");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
console.log("window.productCache is not defined or null");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// IMPORTANT: Check for the exact structure mentioned in the requirement
|
if (window.productCache &&
|
||||||
// window.productCache = {"categoryTree_209":{"categoryTree": ...}}
|
window.productCache["categoryTree_209"] &&
|
||||||
const hasCache = typeof window.productCache === 'object' &&
|
window.productCache["categoryTree_209"].categoryTree) {
|
||||||
window.productCache !== null &&
|
console.log("Found categoryTree_209.categoryTree in cache");
|
||||||
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");
|
|
||||||
|
|
||||||
// Check for specific category data in cache
|
// Check for specific category data in cache
|
||||||
const cachedData = getCachedCategoryData(categoryId);
|
const cachedData = getCachedCategoryData(categoryId);
|
||||||
console.log("Has cached category data:", !!cachedData);
|
|
||||||
|
|
||||||
if (cachedData) {
|
if (cachedData) {
|
||||||
console.log("✅ Using cached category data for", categoryId);
|
console.log("Using cached category data for", categoryId);
|
||||||
this.processDataWithCategoryTree(cachedData, categoryId);
|
this.processDataWithCategoryTree(cachedData, categoryId);
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
@@ -367,14 +349,13 @@ class Content extends Component {
|
|||||||
attributes: [],
|
attributes: [],
|
||||||
categoryName: this.getCategoryNameFromTree(categoryId)
|
categoryName: this.getCategoryNameFromTree(categoryId)
|
||||||
};
|
};
|
||||||
console.log("✅ Using category tree data without products");
|
console.log("Using category tree data without products");
|
||||||
console.log("Category name from tree:", emptyResponse.categoryName);
|
|
||||||
this.processDataWithCategoryTree(emptyResponse, categoryId);
|
this.processDataWithCategoryTree(emptyResponse, categoryId);
|
||||||
return;
|
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
|
// Only if we don't have the category tree in cache, proceed with socket.io query
|
||||||
console.log(`Registering for productList:${categoryId}`);
|
console.log(`Registering for productList:${categoryId}`);
|
||||||
|
|||||||
@@ -40,23 +40,11 @@ const getProductCache = () => {
|
|||||||
const initializeCategories = (language = 'en') => {
|
const initializeCategories = (language = 'en') => {
|
||||||
const productCache = getProductCache();
|
const productCache = getProductCache();
|
||||||
|
|
||||||
if (productCache && productCache[`categoryTree_209_${language}`]) {
|
// Try language-specific cache first, then fallback to default
|
||||||
const cached = productCache[`categoryTree_209_${language}`];
|
const cached = productCache?.[`categoryTree_209_${language}`]?.categoryTree ||
|
||||||
if (cached.categoryTree) {
|
(language === 'de' && productCache?.["categoryTree_209"]?.categoryTree);
|
||||||
return processCategoryTree(cached.categoryTree);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only fallback to old cache format if we're looking for German (default language)
|
return cached ? processCategoryTree(cached) : [];
|
||||||
// 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return [];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const SharedCarousel = () => {
|
const SharedCarousel = () => {
|
||||||
@@ -92,46 +80,49 @@ const SharedCarousel = () => {
|
|||||||
}, [i18n]);
|
}, [i18n]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (
|
// Only fetch if we don't have categories
|
||||||
rootCategories.length === 0 &&
|
if (rootCategories.length === 0 && typeof window !== "undefined") {
|
||||||
typeof window !== "undefined"
|
const productCache = getProductCache();
|
||||||
) {
|
const hasCache = productCache?.[`categoryTree_209_${currentLanguage}`]?.categoryTree ||
|
||||||
console.log("SharedCarousel: Fetching categories by ignoring",window.productCache);
|
(currentLanguage === 'de' && productCache?.["categoryTree_209"]?.categoryTree);
|
||||||
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) {
|
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
|
// Store in cache with language-specific key
|
||||||
try {
|
try {
|
||||||
if (!window.productCache) window.productCache = {};
|
if (!window.productCache) window.productCache = {};
|
||||||
window.productCache[`categoryTree_209_${currentLanguage}`] = {
|
window.productCache[`categoryTree_209_${currentLanguage}`] = {
|
||||||
categoryTree: categoryTreeToUse,
|
categoryTree: response.categoryTree,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
}
|
}
|
||||||
const newCategories = categoryTreeToUse.children || [];
|
const newCategories = response.categoryTree.children || [];
|
||||||
setRootCategories(newCategories);
|
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]);
|
}, [rootCategories.length, currentLanguage]);
|
||||||
|
|
||||||
|
|||||||
@@ -162,17 +162,11 @@ class CategoryList extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fetchCategories = () => {
|
fetchCategories = () => {
|
||||||
|
|
||||||
if (this.state.fetchedCategories) {
|
if (this.state.fetchedCategories) {
|
||||||
console.log('Categories already fetched, skipping');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get current language from state
|
|
||||||
const currentLanguage = this.state.currentLanguage || 'de';
|
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) ||
|
const windowObj = (typeof global !== "undefined" && global.window) ||
|
||||||
(typeof window !== "undefined" && window);
|
(typeof window !== "undefined" && window);
|
||||||
|
|
||||||
@@ -180,56 +174,21 @@ class CategoryList extends Component {
|
|||||||
windowObj.productCache = {};
|
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}`;
|
const cacheKey = `categoryTree_209_${currentLanguage}`;
|
||||||
if (windowObj && windowObj.productCache) {
|
const cachedData = windowObj?.productCache?.[cacheKey];
|
||||||
windowObj.productCache[cacheKey] = {
|
|
||||||
fetching: true,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
this.setState({ fetchedCategories: true });
|
|
||||||
|
|
||||||
//console.log('CategoryList: Fetching categories from socket');
|
// Use cache if available
|
||||||
console.log("CategoryList: Fetching categories by ignoring",window.productCache);
|
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 });
|
||||||
window.socketManager.emit("categoryList", { categoryId: 209, language: currentLanguage, requestTranslation: true }, (response) => {
|
window.socketManager.emit("categoryList", { categoryId: 209, language: currentLanguage, requestTranslation: true }, (response) => {
|
||||||
if (response && response.success) {
|
if (response && response.success) {
|
||||||
// Use translated data if available, otherwise fall back to original
|
// Use translated data if available, otherwise fall back to original
|
||||||
|
|||||||
Reference in New Issue
Block a user