} else {
// Clear duplicate groups when switching away from duplicate_rules view
setTicketCreationRuleGroups([]);
setTicketUpdateRuleGroups([]);
setHourlyRuleGroups([]);
}
these code, and
if it is not from fetch api, then log which tab is active log like that
Assistant
Got it! You want to conditionally log which tab is active only when not fetching from API (i.e., when fetchFromApi is false) inside the code block where you handle setting duplicate groups.
Here’s how you can do that, modifying your existing code block:
js
User
no clearing should occur when it is in all rules
Assistant
Thanks for the clarification!
So to summarize your requirement:
User
Assistant
User
useEffect(() => {
if (ruleViewFilter.value === "duplicate_rules") {
if (fetchFromApi) {
console.log("Filtering from Recent Data");
let duplicateGroups = [];
code
if (activeTab === "ticketcreate") {
duplicateGroups = findAndGroupExactDuplicates(ticketCreationRules);
setTicketCreationRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
} else if (activeTab === "ticketupdate") {
duplicateGroups = findAndGroupExactDuplicates(ticketUpdateRules);
setTicketUpdateRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
} else if (activeTab === "hourly") {
duplicateGroups = findAndGroupExactDuplicates(hourlyTriggerRules);
setHourlyRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
}
} else {
console.log(`Duplicate rules view active in ENTITY mode - current tab: ${activeTab}`);
}
} else {
// When switching away from "duplicate_rules", clear groups
setTicketCreationRuleGroups([]);
setTicketUpdateRuleGroups([]);
setHourlyRuleGroups([]);
}
Assistant
if (typeof obj1 === "string" && typeof obj2 === "string") {
return normalizeText(stripHTML4(obj1)) === normalizeText(stripHTML4(obj2));
}
if (
typeof obj1 !== "object" ||
typeof obj2 !== "object" ||
obj1 === null ||
obj2 === null
) {
return false;
}
const keys1 = Object.keys(obj1).sort();
const keys2 = Object.keys(obj2).sort();
if (keys1.length !== keys2.length) return false;
for (const key of keys1) {
if (!keys2.includes(key)) return false;
let val1 = obj1[key];
let val2 = obj2[key];
if (typeof val1 === "string" && typeof val2 === "string") {
val1 = normalizeText(stripHTML4(val1));
val2 = normalizeText(stripHTML4(val2));
}
if (Array.isArray(val1) && Array.isArray(val2)) {
if (val1.length !== val2.length) return false;
const used = new Set();
for (const item1 of val1) {
const matchIndex = val2.findIndex((item2, idx) => {
if (used.has(idx)) return false;
if (deepEqual(item1, item2)) {
used.add(idx);
return true;
}
return false;
});
if (matchIndex === -1) return false;
}
continue;
}
if (typeof val1 === "object" && typeof val2 === "object") {
if (!deepEqual(val1, val2)) return false;
} else if (val1 !== val2) {
return false;
}
}
return true;
};
const normalizeConditions = (conditions) => {
if (!Array.isArray(conditions)) return [];
function extractText(htmlString) {
if (!htmlString || typeof htmlString !== "string") return "";
let text = htmlString.replace(/<[^>]+>/g, "").trim();
code
if (text.toLowerCase().startsWith("if ")) {
text = text.substring(3).trim();
}
// console.log("Actual Text :", text);
return text; // do not convert to lowercase here
}
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 "";
}
// const duplicateGroupsMap = useMemo(() => {
// // groups: array of arrays of duplicate rules with length > 1
// let allRules = [];
// if (activeTab === "ticketcreate") allRules = ticketCreationRules;
// else if (activeTab === "ticketupdate") allRules = ticketUpdateRules;
// else if (activeTab === "hourly") allRules = hourlyTriggerRules;
// // group duplicates, filtered active only
// const groups = groupDuplicates(allRules).filter((g) => g.length > 1);
// // Map rule_id -> isFirstInGroup flag (true only for first rule of each duplicate group)
// const firstRuleIds = new Set();
// groups.forEach((group) => {
// if (group.length > 0) {
// firstRuleIds.add(group[0].id);
// }
// });
// // Return structure for lookup: firstRuleIds set + flattened set of all duplicate IDs
// const duplicateRuleIds = new Set(groups.flat().map((r) => r.id));
// // Flatten and then filter by searchQuery inside this page
// const flattenedRulesOnPage = flattenGroups(groupsToShow);
// const filteredRulesOnPage = getFilteredRules(flattenedRulesOnPage);
// // Filter groups on page based on filteredRules
// const filteredGroupsToShow = groupsToShow
// .map((group) =>
// group.filter((rule) =>
// filteredRulesOnPage.some((filteredRule) => filteredRule.id === rule.id)
// )
// )
// .filter((group) => group.length > 0);
// if (filteredGroupsToShow.length === 0) {
// // No results found after filtering on this page
// return <p style={{ textAlign: "center", marginTop: "20px" }}>1 No Rules Found.;
// }
const deleteRule = async (rule, allRulesList, isRecentData, entityDataForTab) => {
const { id } = rule;
// const matchedRecord = allRulesList.find((rec) => rec.id === id);
// console.log("Matched ID :", matchedRecord);
let automationTypeId;
let currentRules,
setRulesFunc,
groupSetterFunc,
currentTabPage,
tabKey;
code
// console.log("Delete Triggered :", rule);
switch (activeTab) {
case "ticketcreate":
automationTypeId = ticketCreate;
currentRules = ticketCreationRules;
setRulesFunc = setTicketCreationRules;
groupSetterFunc = setTicketCreationRuleGroups;
currentTabPage = currentPage.ticketcreate;
tabKey = "ticketcreate";
break;
case "ticketupdate":
automationTypeId = ticketUpdate;
currentRules = ticketUpdateRules;
setRulesFunc = setTicketUpdateRules;
groupSetterFunc = setTicketUpdateRuleGroups;
currentTabPage = currentPage.ticketupdate;
tabKey = "ticketupdate";
break;
case "hourly":
automationTypeId = hourlyTriggers;
currentRules = hourlyTriggerRules;
setRulesFunc = setHourlyTriggerRules;
groupSetterFunc = setHourlyRuleGroups;
currentTabPage = currentPage.hourly;
tabKey = "hourly";
break;
default:
return;
}
const targetDisplayId = rule.display_id;
if (targetDisplayId && newRulePloadDB6.current) {
try {
await newRulePloadDB6.current.delete(targetDisplayId);
console.log("Deleted From Entity");
} catch (err) { }
}
// if (fetchFromApi) {
// console.log(`Deleting from Recent Data mode. Entity data for tab :`);
// if (activeTab === "ticketcreate") {
// const data = await Filterrecords(ticketCreate, newRulePloadDB6.current);
// const matchedEntityRule = data.find(item => item.rule_id === rule.id);
// if (matchedEntityRule) {
// console.log("Matched entity rule for deletion:", matchedEntityRule);
// console.log("Matched entity rule for deletion id :", matchedEntityRule.display_id);
// try {
// await newRulePloadDB6.current.delete(matchedEntityRule.display_id);
// console.log("Deleted From Entity");
// } catch (err) { }
// } else {
// console.log("No matching entity rule found with rule_id:", rule.id);
// }
// } else if (activeTab === "ticketupdate") {
// const data = await Filterrecords(ticketUpdate, newRulePloadDB6.current);
// const matchedEntityRule = data.find(item => item.rule_id === rule.id);
// if (matchedEntityRule) {
// console.log("Matched entity rule for deletion:", matchedEntityRule);
// console.log("Matched entity rule for deletion id :", matchedEntityRule.display_id);
// } else {
// console.log("No matching entity rule found with rule_id:", rule.id);
// }
// } else if (activeTab === "hourly") {
// const data = await Filterrecords(hourlyTriggers, newRulePloadDB6.current);
// const matchedEntityRule = data.find(item => item.rule_id === rule.id);
// if (matchedEntityRule) {
// console.log("Matched entity rule for deletion:", matchedEntityRule);
// console.log("Matched entity rule for deletion id :", matchedEntityRule.display_id);
// } else {
// console.log("No matching entity rule found with rule_id:", rule.id);
// }
// }
// }
if (fetchFromApi) {
let data;
if (activeTab === "ticketcreate") {
data = await Filterrecords(ticketCreate, newRulePloadDB6.current);
} else if (activeTab === "ticketupdate") {
data = await Filterrecords(ticketUpdate, newRulePloadDB6.current);
} else if (activeTab === "hourly") {
data = await Filterrecords(hourlyTriggers, newRulePloadDB6.current);
}
if (data) {
await deleteFromEntityIfMatched(data, rule);
}
}
try {
const response = await client.request.invokeTemplate("deleterule", {
context: {
automationid: automationTypeId,
ruleid: id,
},
});
if (response.status === 204) {
console.log("Deleted From api too.")
// Remove deleted rule from the current flat rules list
const updatedRules = currentRules.filter((r) => r.id !== id);
setRulesFunc(updatedRules);
if (ruleViewFilter.value === "duplicate_rules") {
// Recalculate duplicate groups with updated rules after deletion
const updatedGroups = groupDuplicates(updatedRules)
.filter((g) => g.length > 1)
// Optional: sort largest groups first or as you prefer
.sort((a, b) => b.length - a.length);
groupSetterFunc(updatedGroups);
// Flatten the updated groups to find rules on current page
const flattenUpdatedGroups = flattenGroups(updatedGroups);
const filteredRules = getFilteredRules(flattenUpdatedGroups);
const paginated = pagination(filteredRules, currentTabPage);
// If current page empty and not first page, shift current page back
if (paginated.length === 0 && currentTabPage > 1) {
setCurrentPage((prev) => ({ ...prev, [tabKey]: Math.max(1, prev[tabKey] - 1) }));
}
} else {
// In "all_rules" mode or others, just clear groups cache (optional)
groupSetterFunc([]);
const filteredRules = getFilteredRules(updatedRules);
const paginated = pagination(filteredRules, currentTabPage);
if (paginated.length === 0 && currentTabPage > 1) {
setCurrentPage((prev) => ({ ...prev, [tabKey]: Math.max(1, prev[tabKey] - 1) }));
}
}
toast.current.trigger({ type: "success", content: "Rule deleted successfully!" });
} else {
toast.current.trigger({ type: "error", content: "Failed to delete rule." });
}
} catch (error) {
console.log(error);
toast.current.trigger({ type: "error", content: "Error deleting rule." });
}
};
const openRuleDetails = async (rule) => {
if (!fetchFromApi) {
console.log("fetchFromApi is false");
console.log("Checking if the rule is in api");
console.log("Clicked Rule ID :", rule.id);
console.log("Clicked Rule Automation Type ID :", rule.automation_type_id);
console.log("Clicked Rule Display ID :", rule.display_id);
// correctly working
code
try {
// Call the API to fetch the rule details using automation_type_id and rule id
const response = await client.request.invokeTemplate("getid", {
context: {
automationid: rule.automation_type_id,
ruleid: rule.id
},
});
// Log the formatted JSON rule details
console.log("Yes it is in Instance. Formatted JSON output:");
console.log(response);
} catch (error) {
console.error("Error fetching rule details:", error);
const status = error.status || error.response?.status || error.statusCode || null;
console.log("Detected status:", status);
if (status === 404) {
console.log("Moving to delete rule from entity.");
toast.current.trigger({ type: "error", content: "Rule not found. Try refreshing the page." });
if (rule.display_id && newRulePloadDB6.current) {
try {
await newRulePloadDB6.current.delete(rule.display_id);
console.log("Deleted from local entity store due to 404.");
} catch (err) {
console.error("Failed to delete from entity store:", err);
}
}
}
}
} else {
console.log("This is Recent Data inthis it will never work.");
}
let groups = [];
if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
else if (activeTab === "hourly") groups = hourlyRuleGroups;
const paginatedGroups = paginateDuplicateGroups(groups, rulesPerPage, searchQuery);
const pageIndex = currentPage[activeTab] - 1;
let startItem = 1;
for (let i = 0; i < pageIndex; i++) {
const groupsToShow = paginatedGroups[i];
if (groupsToShow && groupsToShow.length > 0) {
startItem += flattenGroups(groupsToShow).length;
}
}
return startItem;
};
const getCurrentPageItemCount = (totalItems) => {
code
if (ruleViewFilter.value !== "duplicate_rules") {
const calculatedEnd = currentPage[activeTab] * rulesPerPage;
return Math.min(calculatedEnd, totalItems);
}
// For duplicate_rules
let groups = [];
if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
else if (activeTab === "hourly") groups = hourlyRuleGroups;
const paginatedGroups = paginateDuplicateGroups(groups, rulesPerPage, searchQuery);
// console.log("Paginated Groups:", paginatedGroups);
const pageIndex = currentPage[activeTab] - 1;
// console.log("Current Page Index:", pageIndex);
let cumulativeCount = 0;
for (let i = 0; i <= pageIndex; i++) {
const groupsToShow = paginatedGroups[i];
// console.log(`Groups on Page ${i + 1}:`, groupsToShow);
if (groupsToShow && groupsToShow.length > 0) {
const flatLength = flattenGroups(groupsToShow).length;
// console.log(`Flattened count on Page ${i + 1}:`, flatLength);
cumulativeCount += flatLength;
}
}
// console.log("Final cumulative count:", cumulativeCount);
return cumulativeCount;
};
const getPaginationTotalCount = () => {
if (ruleViewFilter.value === "duplicate_rules") {
let groups = [];
if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
else if (activeTab === "hourly") groups = hourlyRuleGroups;
code
const query = searchQuery.trim().toLowerCase();
// Apply the full filtering logic consistently as in paginateDuplicateGroups
const filteredGroups = groups
.map((group) =>
group.filter((rule) => {
if (!query) return true;
const name = rule.name?.toLowerCase() || '';
const description = rule.description?.toLowerCase() || '';
const customSummary =
typeof rule.summary === 'string'
? rule.summary.toLowerCase()
: rule.summary?.summary?.toLowerCase() || '';
const conditionStrings = [
...(rule.summary?.conditions?.condition_set_1 || []),
...(rule.summary?.conditions?.condition_set_2 || [])
].join(' ').toLowerCase();
const actionStrings = (rule.summary?.actions || []).join(' ').toLowerCase();
// You can add more deep condition/action fields here to match your full search logic if needed
const combinedSearchData = [
name,
description,
conditionStrings,
actionStrings,
customSummary
].join(' ');
return combinedSearchData.includes(query);
})
)
.filter((group) => group.length > 0);
return filteredGroups.reduce((acc, group) => acc + group.length, 0);
} else {
// Non-duplicate view: existing logic
return getCurrentTotalCount();
}
};
// Helper function to paginate a single group of items
const paginateGroup = (group, itemsPerPage, currentPage) => {
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = Math.min(startIndex + itemsPerPage, group.length);
return group.slice(startIndex, endIndex);
};
// Helper function to paginate groups (assuming groups are an array of arrays)
const paginateGroups = (groups, itemsPerPage, currentPage) => {
// Flatten the groups to paginate them as a single list
let allItems = [];
for (const group of groups) {
allItems = allItems.concat(group);
}
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = Math.min(startIndex + itemsPerPage, allItems.length);
const pageItems = allItems.slice(startIndex, endIndex);
// Reconstruct the page based on the original group structure
const pageGroups = [];
let currentIndex = 0;
for (const group of groups) {
let groupIndex = 0;
while (groupIndex < group.length && pageItems.includes(group[groupIndex])) {
if (!pageGroups[pageGroups.length - 1] || pageGroups[pageGroups.length - 1].length >= itemsPerPage) {
pageGroups.push([]);
}
pageGroups[pageGroups.length - 1].push(group[groupIndex]);
groupIndex++;
}
currentIndex += group.length;
}
return pageItems;
};
in this code, on changing to duplicate_rules in entity (not recent data) log which tab is
To log which tab is active when switching to the "duplicate_rules" view in entity mode (i.e., when fetchFromApi is false), you should add a logging statement inside the useEffect that responds to ruleViewFilter changes (or where duplicate groups are computed/set).
Where to add the log?
You already have a useEffect that runs when ruleViewFilter, activeTab, or the rule lists change:
Modify this effect by adding a log that indicates which tab is processing duplicate groups, but only when in entity mode (fetchFromApi is false). Something like:
js
useEffect(() => {
if (ruleViewFilter.value === "duplicate_rules") {
if (!fetchFromApi) {
console.log(`Switching to duplicate_rules view in entity mode. Active tab is: ${activeTab}`);
}
let duplicateGroups = [];
if (activeTab === "ticketcreate") {
duplicateGroups = findAndGroupExactDuplicates(ticketCreationRules);
setTicketCreationRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
} else if (activeTab === "ticketupdate") {
duplicateGroups = findAndGroupExactDuplicates(ticketUpdateRules);
setTicketUpdateRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
} else if (activeTab === "hourly") {
duplicateGroups = findAndGroupExactDuplicates(hourlyTriggerRules);
setHourlyRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
}
} else {
// Clear duplicate groups when switching away from duplicate_rules view
setTicketCreationRuleGroups([]);
setTicketUpdateRuleGroups([]);
setHourlyRuleGroups([]);
}
}, [ruleViewFilter, activeTab, ticketCreationRules, ticketUpdateRules, hourlyTriggerRules, fetchFromApi]);
Note: Added fetchFromApi in dependency array to make sure it's up to date.
Summary:
Log inside the useEffect which processes the duplicate groups.
Only log when ruleViewFilter.value === "duplicate_rules" and fetchFromApi is false (meaning “entity mode”).
Output the current activeTab.
If you want to log any change to ruleViewFilter to duplicate_rules, you can also add a separate effect for clarity:
Let me know if you want a runnable code snippet or help with further customizations!
if (ruleViewFilter.value === "duplicate_rules") {
let duplicateGroups = [];
if (fetchFromApi) {
if (activeTab === "ticketcreate") {
duplicateGroups = findAndGroupExactDuplicates(ticketCreationRules);
setTicketCreationRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
} else if (activeTab === "ticketupdate") {
duplicateGroups = findAndGroupExactDuplicates(ticketUpdateRules);
setTicketUpdateRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
} else if (activeTab === "hourly") {
duplicateGroups = findAndGroupExactDuplicates(hourlyTriggerRules);
setHourlyRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
}
} else {
// **Log active tab only if NOT fetchFromApi**
console.log(`Duplicate rules view active in ENTITY mode - current tab: ${activeTab}`);
// Clear duplicates groups or do whatever else needed here:
setTicketCreationRuleGroups([]);
setTicketUpdateRuleGroups([]);
setHourlyRuleGroups([]);
}
} else {
// Clear duplicate groups when switching away from duplicate_rules view
setTicketCreationRuleGroups([]);
setTicketUpdateRuleGroups([]);
setHourlyRuleGroups([]);
}
Summary:
When ruleViewFilter.value === "duplicate_rules":
If fetchFromApi is true, run your duplicate grouping logic per tab.
If fetchFromApi is false (meaning data is from entity/database), log the active tab and clear duplicate groups.
When ruleViewFilter is anything else, clear all duplicates groups.
Would you want me to help you refactor this inside your React useEffect?
When ruleViewFilter.value === "duplicate_rules":
If fetchFromApi is true → group duplicates per active tab (as you already do).
If fetchFromApi is false → just log the active tab (and don't clear any duplicate groups here).
When ruleViewFilter.value !== "duplicate_rules" (i.e., in "all_rules" or other views):
Clear duplicate groups.
Here’s the modified code block with this behavior implemented:
js
if (ruleViewFilter.value === "duplicate_rules") {
if (fetchFromApi) {
let duplicateGroups = [];
if (activeTab === "ticketcreate") {
duplicateGroups = findAndGroupExactDuplicates(ticketCreationRules);
setTicketCreationRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
} else if (activeTab === "ticketupdate") {
duplicateGroups = findAndGroupExactDuplicates(ticketUpdateRules);
setTicketUpdateRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
} else if (activeTab === "hourly") {
duplicateGroups = findAndGroupExactDuplicates(hourlyTriggerRules);
setHourlyRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
}
} else {
// Log activeTab when NOT fetchFromApi in duplicate_rules view
console.log(`Duplicate rules view active in ENTITY mode - current tab: ${activeTab}`);
// Do NOT clear here, retain existing groups
}
} else {
// Clear duplicate groups when in 'all_rules' or other views
setTicketCreationRuleGroups([]);
setTicketUpdateRuleGroups([]);
setHourlyRuleGroups([]);
}
Explanation
The duplicate groups are only updated/refreshed when fetchFromApi is true and duplicate_rules view is active.
When in duplicate_rules view but fetchFromApi is false, no changes are made except log the active tab.
The clearing of duplicate groups happens only if the view is not duplicate_rules.
Where to put this?
Put this inside the existing useEffect you already have for monitoring:
jsx
useEffect(() => {
// Your code above here
}, [ruleViewFilter, activeTab, ticketCreationRules, ticketUpdateRules, hourlyTriggerRules, fetchFromApi]);
Let me know if you want me to provide a full snippet with the useEffect including this logic!
ncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
at renderWithHooks (react-dom.development.js:14997:1)
at mountIndeterminateComponent (react-dom.development.js:17811:1)
at beginWork (react-dom.development.js:19049:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at beginWork1(react−dom.development.js:23964:1)atperformUnitOfWork(r1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22779
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
(anonymous) @ react-dom.development.js:11327
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority1 @ react-dom.development.js:22420
discreteUpdates @ react-dom.development.js:3756
dispatchDiscreteEvent @ react-dom.development.js:5889Understand this error
react-dom.development.js:20085 The above error occurred in the component:
code
at AutomationTabs (http://localhost:10001/iframe/agent/scripts/main.a87fe8a6.js:1402:23)
at div
at div
at App (http://localhost:10001/iframe/agent/scripts/main.a87fe8a6.js:54:21)
at Root (http://localhost:10001/iframe/agent/scripts/main.a87fe8a6.js:4708:21)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:20085
update.callback @ react-dom.development.js:20118
callCallback @ react-dom.development.js:12318
commitUpdateQueue @ react-dom.development.js:12339
commitLifeCycles @ react-dom.development.js:20736
commitLayoutEffects @ react-dom.development.js:23426
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
commitRootImpl @ react-dom.development.js:23151
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority1 @ react-dom.development.js:11276
flushSyncCallbackQueueImpl @ react-dom.development.js:11322
flushSyncCallbackQueue @ react-dom.development.js:11309
discreteUpdates1 (react-dom.development.js:23964:1)
at performUnitOfWork (react-dom.development.js:22779:1)
at workLoopSync (react-dom.development.js:22707:1)
at renderRootSync (react-dom.development.js:22670:1)
The "Too many re-renders" error generally means that something in your component causes it to update state during render (or in a way that triggers an immediate state update on every render), resulting in React entering an infinite render loop.
Common causes:
Calling a state setter like setState directly inside the main body of the component (or inside a render function) without a condition that prevents it from running on every render.
State updates inside useEffect with dependencies that cause the effect to trigger repeatedly.
Setting state inside render (instead of inside event handlers or effects).
Calling functions that internally set state directly within JSX or render.
Where this might happen in your code
Looking at the snippet you shared and your previous request, the likely cause is:
js
if (ruleViewFilter.value === "duplicate_rules") {
if (fetchFromApi) {
let duplicateGroups = [];
if (activeTab === "ticketcreate") {
duplicateGroups = findAndGroupExactDuplicates(ticketCreationRules);
setTicketCreationRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
} else if (activeTab === "ticketupdate") {
duplicateGroups = findAndGroupExactDuplicates(ticketUpdateRules);
setTicketUpdateRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
} else if (activeTab === "hourly") {
duplicateGroups = findAndGroupExactDuplicates(hourlyTriggerRules);
setHourlyRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
}
} else {
console.log(`Duplicate rules view active in ENTITY mode - current tab: ${activeTab}`);
// No state change here, so should be okay
}
} else {
setTicketCreationRuleGroups([]);
setTicketUpdateRuleGroups([]);
setHourlyRuleGroups([]);
}
If this is inside the React component body (not inside a useEffect), every render will call setTicketCreationRuleGroups (or similar), which triggers another render, creating an infinite loop.
How to fix this
Wrap this logic inside a useEffect hook:
jsx
useEffect(() => {
if (ruleViewFilter.value === "duplicate_rules") {
if (fetchFromApi) {
let duplicateGroups = [];
if (activeTab === "ticketcreate") {
duplicateGroups = findAndGroupExactDuplicates(ticketCreationRules);
setTicketCreationRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
} else if (activeTab === "ticketupdate") {
duplicateGroups = findAndGroupExactDuplicates(ticketUpdateRules);
setTicketUpdateRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
} else if (activeTab === "hourly") {
duplicateGroups = findAndGroupExactDuplicates(hourlyTriggerRules);
setHourlyRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
}
} else {
console.log(`Duplicate rules view active in ENTITY mode - current tab: ${activeTab}`);
// No state update, so no infinite rerender here
}
} else {
// When switching away from "duplicate_rules", clear groups
setTicketCreationRuleGroups([]);
setTicketUpdateRuleGroups([]);
setHourlyRuleGroups([]);
}
}, [ruleViewFilter, activeTab, ticketCreationRules, ticketUpdateRules, hourlyTriggerRules, fetchFromApi]);
Explanation
useEffect runs after render, and state changes inside it cause a new render, but React handles that safely.
React will not run the effect again (and cause a loop) if the dependencies don’t change.
If your setState calls are within render, this will cause infinite loops.
Additional debugging tips
Check all places in your component where you call setState.
Make sure these calls are not directly executed in the render body without any conditional or inside effects/event handlers.
If you must call something conditionally during render, store the values as refs or state outside the render or inside useMemo/useEffect.
Bottom line:
Move your duplicate groups update logic inside a useEffect with the correct dependency array — do NOT call any state setters directly in the component render function.
If you want, I can help rewrite and integrate the full useEffect code for you. Just ask!
Your useEffect logic looks basically correct for updating duplicateRulesGroups when switching to duplicate rules view and fetching from API, and only logging in entity mode.
If you say "it seems it is not working correctly", here’s some common things to check and suggestions:
1. Confirm the deps and data changes actually trigger useEffect
Are you sure that ticketCreationRules, ticketUpdateRules, or hourlyTriggerRules actually change when you expect them to?
E.g., if these arrays are the same by reference, the effect won’t trigger.
You can temporarily add a console.log inside the effect to verify that it is triggered:
If you want to run some logic only when fetchFromApi is false and duplicate_rules active, add a separate effect to avoid mixing with the grouping effect:
jsx
useEffect(() => {
if (ruleViewFilter.value === "duplicate_rules" && !fetchFromApi) {
console.log(`Duplicate rules view active in ENTITY mode - current tab: ${activeTab}`);
// You can add any other logic here if needed
}
}, [ruleViewFilter, activeTab, fetchFromApi]);
6. Check that no other conflicting updates or renders happen
If you have other code that resets these groups or interferes, that might be why it looks like it's "not working".
7. Example minimal debugging output
You can also explicitly verify your states after setState calls with a useEffect watcher: