// Utility: clean and normalize text
const cleanText = (text) =>
String(text || "")
.toLowerCase()
.replace(/<img[^>]>/gi, "") // remove tags
.replace(/ /gi, " ") // replace non-breaking space
.replace(/<[^>]>/g, "") // remove any other HTML tags
.replace(/[,.]/g, "") // remove commas and periods
.replace(/([a-zA-Z])(\d)/g, "12") // split letters & digits
.replace(/(\d)([a-zA-Z])/g, "12")
.replace(/\s+/g, " ") // collapse spaces
.trim()
.replace(/\bcomma\b\s*\bfull\s*stop\b/g, "comma fullstop");
// Normalize the condition parts similarly to original code logic
const normalizeConditionParts = (rawConditions) => {
let parts = [];
if (typeof rawConditions === "string") {
parts = rawConditions.split(",");
} else if (Array.isArray(rawConditions)) {
parts = rawConditions;
} else {
// if conditions is null, undefined, object etc.
parts = [];
}
for (let part of parts) {
const cleaned = cleanText(part);
if (cleaned === "condition set 1") {
currentSet = set1;
continue;
}
if (cleaned === "condition set 2") {
currentSet = set2;
continue;
}
if (currentSet) currentSet.push(cleaned);
}
To ensure that when switching between entity (fetchFromApi === false) and recent (fetchFromApi === true) data, the filter (ruleViewFilter) should always be "all_rules" and not "duplicate_rules", you need to adjust the effect that runs on tab change and fetch mode toggle.
Fix:
Modify the effect where activeTab and/or fetchFromApi changes so that whenever you switch between entity and recent data (fetchFromApi changes) or tabs, the ruleViewFilter is reset to "all_rules".
Replace this part:
// Existing effect resetting filter on tab change
useEffect(() => {
setCurrentPage((prev) => ({
...prev,
[activeTab]: 1,
}));
if (ruleViewFilter.value === "duplicate_rules") {
setRuleViewFilter(ruleViewOptions[0]); // Reset to 'All Rules' on tab switch
}
}, [activeTab]);
User
also this feature :
on runing recent data, only fetch one time for each tab and reuse that datta until then when user refresh / clik Going back.
Assistant
User
how to verify that this functionality is running
Assistant
To verify that the "fetch recent data once per tab and reuse until back/reset" functionality is working as expected, you can do the following:
// Imperatively open modal if showDeleteModal became true
useEffect(() => {
if (showDeleteModal && modalRef.current) {
modalRef.current.open();
}
}, [showDeleteModal]);
function extractText(htmlString) {
if (!htmlString || typeof htmlString !== "string") return "";
let text = htmlString.replace(/<[^>]+>/g, "").trim();
if (text.toLowerCase().startsWith("if ")) {
text = text.substring(3).trim();
}
return text.toLowerCase();
}
function generateSummary(summary) {
if (!summary) return "";
if (typeof summary === "string") {
return summary;
}
let conditionTexts = [];
if (summary.conditions) {
for (const setKey in summary.conditions) {
if (Object.prototype.hasOwnProperty.call(summary.conditions, setKey)) {
const conditionsVal = summary.conditions[setKey];
const conditionsArray = Array.isArray(conditionsVal)
? conditionsVal
: [conditionsVal];
const cleanConditions = conditionsArray.map(extractText);
conditionTexts.push(cleanConditions.join(", "));
}
}
}
const conditionsStr = conditionTexts.join(", ");
let actionsStr = "";
if (summary.actions && Array.isArray(summary.actions)) {
const cleanActions = summary.actions.map(extractText);
actionsStr = cleanActions.join(", ");
}
if (conditionsStr && actionsStr) {
return if ${conditionsStr}, then ${actionsStr};
} else if (conditionsStr) {
return if ${conditionsStr};
} else if (actionsStr) {
return actionsStr;
}
return "";
}
<fw-input
ref={inputRef}
icon-left="search"
hint-text="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{
width: "400px",
height: "60px",
fontSize: "18px",
}}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
setSearchQuery(""); // Clear filter to show all rules
}
setSearchTerm(val);
if (showSearchHint) setShowSearchHint(false);
if (inputState !== "normal") setInputState("normal");
useEffect(() => {
setCurrentPage((prev) => ({
...prev,
[activeTab]: 1,
}));
// Always reset filter to "All Rules" when switching tabs or switching between entity/recent
setRuleViewFilter(ruleViewOptions[0]);
}, [activeTab, fetchFromApi]);
Explanation:
Now whenever either activeTab or fetchFromApi changes, ruleViewFilter is reset to default "all_rules".
This prevents the filter from staying on "duplicate_rules" when switching between entity vs recent data or tabs.
That’s the minimal/precise change needed in your component to achieve the requested behavior.
Got it! You want the "recent data" (fetchFromApi === true) to fetch only once per tab during the session and reuse that fetched data until the user either refreshes the app or toggles back to entity mode (fetchFromApi === false, i.e., clicks "Going Back").
How to do this:
Maintain a cache to store recent data fetched per tab.
On fetch for recent data, check if cached data for the tab exists:
If yes, reuse cached data, do not fetch again.
If no, fetch from API and cache it.
On toggle back to entity mode (fetchFromApi === false), clear caches or you can leave them, but on next toggle back to recent mode, cached data will still be used unless you want to clear it on toggle.
Implementation:
Add a React state for caching recent data per tab, e.g.:
Then update your effect that fetches data (fetchOnTabOrModeChange) to:
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
setErrorMessage(null);
try {
let error = null;
if (fetchFromApi) {
// Check if data already cached for this tab
if (recentDataCache[activeTab]) {
// Use cached data - just set the state accordingly
if (activeTab === "ticketcreate") {
setTicketCreationRules(recentDataCache.ticketcreate);
} else if (activeTab === "ticketupdate") {
setTicketUpdateRules(recentDataCache.ticketupdate);
} else if (activeTab === "hourly") {
setHourlyTriggerRules(recentDataCache.hourly);
}
} else {
// No cache - fetch from API and store in cache
if (activeTab === "ticketcreate") {
error = await getTicketCreationRules(client, (data) => {
setTicketCreationRules(data);
setRecentDataCache((prev) => ({ ...prev, ticketcreate: data }));
});
} else if (activeTab === "ticketupdate") {
error = await getTicketUpdationRules(client, (data) => {
setTicketUpdateRules(data);
setRecentDataCache((prev) => ({ ...prev, ticketupdate: data }));
});
} else if (activeTab === "hourly") {
error = await getHourlyRules(client, (data) => {
setHourlyTriggerRules(data);
setRecentDataCache((prev) => ({ ...prev, hourly: data }));
});
}
}
await getAgents(client, setAgent);
} else {
// Entity mode - fetch fresh from entity DB always (do not cache)
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
if (activeTab === "ticketcreate") {
const data = await Filterrecords(ticketCreate, newRulePloadDB5.current);
setTicketCreationRules(data);
} else if (activeTab === "ticketupdate") {
const data = await Filterrecords(ticketUpdate, newRulePloadDB5.current);
setTicketUpdateRules(data);
} else if (activeTab === "hourly") {
const data = await Filterrecords(hourlyTriggers, newRulePloadDB5.current);
setHourlyTriggerRules(data);
}
// Clear recent data cache since we're back to entity mode
setRecentDataCache({
ticketcreate: null,
ticketupdate: null,
hourly: null,
});
}
if (error) {
setErrorMessage(error);
}
} catch (err) {
console.error("Error fetching data:", err);
setErrorMessage("An unexpected error occurred while fetching data.");
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
Explanation of key points:
recentDataCache holds data for the 3 tabs, default null.
On fetchFromApi === true, first check if data already exists for current tab in cache.
If yes, set that data to state directly — no fetch call.
If no, fetch then store into cache & set state.
On switching back to entity (fetchFromApi === false), data fetched fresh from entity DB and clear the cache, so next toggle to recent fetches fresh data again.
This way, recent data fetch is 1 time per tab per toggle to recent mode.
If you want me to provide the exact diff or code block ready to replace, let me know!
1. Add console logs to track fetching and cache usage
In your fetchOnTabOrModeChange effect, add console logs at the key points:
if (fetchFromApi) {
if (recentDataCache[activeTab]) {
console.log(`[Cache Hit] Using cached recent data for tab: ${activeTab}`);
// ...
} else {
console.log(`[Cache Miss] Fetching recent data for tab: ${activeTab}`);
// ...
}
} else {
console.log(`[Mode] Switched to entity mode. Clearing recent data cache.`);
// ...
}
2. Test behavior in UI
Start with fetchFromApi === false (entity data).
Switch tab to "ticketcreate" (or any tab).
Click "Get Recent Data" button (toggles fetchFromApi to true).
Observe console: should see "Cache Miss" log for that tab and API call firing.
Switch to another tab.
Console: "Cache Miss" log for that tab and API call.
Switch back to the previous tab again while fetchFromApi === true.
Console: "Cache Hit" log — confirming cached data used, no API call.
Click "Back" button (toggles fetchFromApi back to false).
Console: logs clearing cache.
Toggle again to recent data (fetchFromApi === true).
Console: "Cache Miss" for all tabs again (fetch fresh).
3. Visual validation
Monitor network tab in browser dev tools:
API calls/fetches for recent data should fire once per tab per toggle to recent mode.
No fetch requests when switching tabs if data is cached.
UI data should update accordingly and not flicker or reload unnecessarily when switching tabs if cached.
4. Optional: Add Toast or UI message for debugging
You could temporarily add a small indicator when cache hit vs miss happens, e.g.:
toast.current.trigger({
type: "info",
content: `[Debug] ${recentDataCache[activeTab] ? 'Using cached data' : 'Fetching new data'} for ${activeTab}`,
});
Make sure to remove this after validation.
Summary:
Console logs are quickest and easiest for confirmation.
Network dev tools verify API calls.
UI/states reflecting data without refetch confirms cache reuse.
Cache clearing confirmation on toggle back ensures reset working.
If you want, I can help you add these logs/code snippets directly in your existing code!
Sure! Below is the updated key part of your useEffect for fetching data, including:
Console logs for cache hits/misses and mode switches
Handling cached agents in the same way as rules per tab
Also caching agents only once when fetching recent data, reusing cached agents until backing off or refreshing
Step 1: Add new state to cache agents fetched on recent data mode
Add this in your component state declarations near recentDataCache:
just add log to verify the cache/uncache not for agent
Certainly! Below is your existing useEffect updated to include console logs indicating cache hits/misses for rules data only (not for agents):
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
setErrorMessage(null);
try {
let error = null;
if (fetchFromApi) {
// Check if data already cached for this tab
if (recentDataCache[activeTab]) {
console.log(`[Cache Hit] Using cached recent rules data for tab: ${activeTab}`);
// Use cached data - just set the state accordingly
if (activeTab === "ticketcreate") {
setTicketCreationRules(recentDataCache.ticketcreate);
} else if (activeTab === "ticketupdate") {
setTicketUpdateRules(recentDataCache.ticketupdate);
} else if (activeTab === "hourly") {
setHourlyTriggerRules(recentDataCache.hourly);
}
} else {
console.log(`[Cache Miss] Fetching recent rules data for tab: ${activeTab}`);
// No cache - fetch from API and store in cache
if (activeTab === "ticketcreate") {
error = await getTicketCreationRules(client, (data) => {
setTicketCreationRules(data);
setRecentDataCache((prev) => ({ ...prev, ticketcreate: data }));
});
} else if (activeTab === "ticketupdate") {
error = await getTicketUpdationRules(client, (data) => {
setTicketUpdateRules(data);
setRecentDataCache((prev) => ({ ...prev, ticketupdate: data }));
});
} else if (activeTab === "hourly") {
error = await getHourlyRules(client, (data) => {
setHourlyTriggerRules(data);
setRecentDataCache((prev) => ({ ...prev, hourly: data }));
});
}
}
await getAgents(client, setAgent);
} else {
// Entity mode - fetch fresh from entity DB always (do not cache)
console.log(`[Mode] Switched to entity mode. Clearing recent rules data cache.`);
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
if (activeTab === "ticketcreate") {
const data = await Filterrecords(ticketCreate, newRulePloadDB5.current);
setTicketCreationRules(data);
} else if (activeTab === "ticketupdate") {
const data = await Filterrecords(ticketUpdate, newRulePloadDB5.current);
setTicketUpdateRules(data);
} else if (activeTab === "hourly") {
const data = await Filterrecords(hourlyTriggers, newRulePloadDB5.current);
setHourlyTriggerRules(data);
}
// Clear recent data cache since we're back to entity mode
setRecentDataCache({
ticketcreate: null,
ticketupdate: null,
hourly: null,
});
}
if (error) {
setErrorMessage(error);
}
} catch (err) {
console.error("Error fetching data:", err);
setErrorMessage("An unexpected error occurred while fetching data.");
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
What was added:
console.log on cache hit: [Cache Hit] Using cached recent rules data for tab: ${activeTab}
console.log on cache miss (fetch): [Cache Miss] Fetching recent rules data for tab: ${activeTab}
Log when switching back to entity mode and clearing cache: [Mode] Switched to entity mode. Clearing recent rules data cache.
You can watch the browser console to verify when data is reused from cache vs fetched fresh. This meets your request to only log for rules caching, not agents.
just add log to verify the data is cache./uncached
Certainly! Here's your updated useEffect with console logs added to verify when the data is fetched fresh (cache miss) or when cached data is reused (cache hit):
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
setErrorMessage(null);
try {
let error = null;
if (fetchFromApi) {
// Check if data already cached for this tab
if (recentDataCache[activeTab]) {
console.log(`[Cache Hit] Using cached recent data for tab: ${activeTab}`);
// Use cached data - just set the state accordingly
if (activeTab === "ticketcreate") {
setTicketCreationRules(recentDataCache.ticketcreate);
} else if (activeTab === "ticketupdate") {
setTicketUpdateRules(recentDataCache.ticketupdate);
} else if (activeTab === "hourly") {
setHourlyTriggerRules(recentDataCache.hourly);
}
} else {
console.log(`[Cache Miss] Fetching recent data for tab: ${activeTab}`);
// No cache - fetch from API and store in cache
if (activeTab === "ticketcreate") {
error = await getTicketCreationRules(client, (data) => {
setTicketCreationRules(data);
setRecentDataCache((prev) => ({ ...prev, ticketcreate: data }));
});
} else if (activeTab === "ticketupdate") {
error = await getTicketUpdationRules(client, (data) => {
setTicketUpdateRules(data);
setRecentDataCache((prev) => ({ ...prev, ticketupdate: data }));
});
} else if (activeTab === "hourly") {
error = await getHourlyRules(client, (data) => {
setHourlyTriggerRules(data);
setRecentDataCache((prev) => ({ ...prev, hourly: data }));
});
}
}
await getAgents(client, setAgent);
} else {
console.log(`[Entity Mode] Fetching fresh data for tab: ${activeTab} and clearing cache.`);
// Entity mode - fetch fresh from entity DB always (do not cache)
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
if (activeTab === "ticketcreate") {
const data = await Filterrecords(ticketCreate, newRulePloadDB5.current);
setTicketCreationRules(data);
} else if (activeTab === "ticketupdate") {
const data = await Filterrecords(ticketUpdate, newRulePloadDB5.current);
setTicketUpdateRules(data);
} else if (activeTab === "hourly") {
const data = await Filterrecords(hourlyTriggers, newRulePloadDB5.current);
setHourlyTriggerRules(data);
}
// Clear recent data cache since we're back to entity mode
setRecentDataCache({
ticketcreate: null,
ticketupdate: null,
hourly: null,
});
}
if (error) {
setErrorMessage(error);
}
} catch (err) {
console.error("Error fetching data:", err);
setErrorMessage("An unexpected error occurred while fetching data.");
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
Summary of added logs:
Logs on cache hit: [Cache Hit] Using cached recent data for tab: {activeTab}
Logs on cache miss (fetch): [Cache Miss] Fetching recent data for tab: {activeTab}
Logs on entity mode fetch and cache clearing: [Entity Mode] Fetching fresh data for tab: {activeTab} and clearing cache.
These logs will help you verify in the browser console whether cached data is reused or fresh data is fetched each time.
now make agent like that too but when making like that why it is not sending agents so that cause error like not showing the name only showing the id
To apply the same caching logic to agents like you do for rules and to avoid agents not showing properly (showing only IDs), you need to:
Cache the agents fetched in recent mode.
Use the cached agents if available instead of fetching again.
Clear the cached agents when switching back to entity mode.
Important: When using cached agents, make sure you actually update your agent state after setting it from cache, to cause the UI to re-render with agent names instead of just IDs.
Why might agents not show correctly?
If agent state isn't updated properly with the fetched or cached agents, your UI falls back to showing IDs instead of names.
If the cached agents are stale or not set at all, agent.find(...) fails to resolve names.
If agents are loaded asynchronously, you must ensure your UI only tries to resolve agent names afteragent is set.
Solution: Add caching and proper agent state updates for agents