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 Automation Type ID :", rule.display_id);
try {
const response = await client.request.invokeTemplate("getid", {
context: {
automationid: rule.automation_type_id,
ruleid: rule.id
},
});
if (response.status === 404) {
// Show error toast
toast.current.trigger({ type: "error", content: "Rule not found. Removing from Entity." });
// If display_id exists and entity store reference exists
if (rule.display_id && newRulePloadDB6.current) {
try {
// Delete the item from local entity store using display_id
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 if (response.status >= 200 && response.status < 300) {
const ruleDetails = response.data || response;
let parsedResponse;
try {
parsedResponse = typeof ruleDetails.response === "string"
? JSON.parse(ruleDetails.response)
: ruleDetails.response;
} catch (e) {
console.error("Failed to parse rule details response", e);
return;
}
console.log("Yess it is in Instance. Formatted JSON output:");
console.log(JSON.stringify(parsedResponse, null, 2));
toast.current.trigger({ type: "success", content: "Rules Fetched Successfully." });
} else {
toast.current.trigger({ type: "error", content: "Failed to fetch rule details." });
}
} catch (error) {
console.error("Error fetching rule details:", error);
toast.current.trigger({ type: "error", content: "Error fetching rule details." });
}
Assistant
User
Assistant
Good question!
In your deleteRule function, the entity (local database reference) used for deletion is accessed via the newRulePloadDB6React ref:
js
User
const openRuleDetails = async (rule) => {
// Log the input rule details for debugging
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);
code
Assistant
User
Assistant
};
give me clear\
Certainly! Here's a clear explanation of what your openRuleDetails function does, along with some comments for clarity:
Function Purpose:
The openRuleDetails function tries to fetch detailed information about a given "rule" from an API. Depending on the results, it either handles a "not found" case, processes the returned data, or shows relevant error messages.
Step-by-step Explanation:
js
const openRuleDetails = async (rule) => {
// Log the input rule details for debugging
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);
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
},
});
// Handle case when API returns 404 (Not Found)
if (response.status === 404) {
// Show error notification to user
toast.current.trigger({ type: "error", content: "Rule not found. Removing from Entity." });
// If the rule has display_id and local entity store exists, delete the entry
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);
}
}
}
// Handle successful response (status code 200-299)
else if (response.status >= 200 && response.status < 300) {
// Extract detailed rule data from API response
const ruleDetails = response.data || response;
let parsedResponse;
try {
// Parse rule details response if it's a JSON string, otherwise use it directly
parsedResponse = typeof ruleDetails.response === "string"
? JSON.parse(ruleDetails.response)
: ruleDetails.response;
} catch (e) {
console.error("Failed to parse rule details response", e);
return; // Exit if parsing fails
}
// Log the formatted JSON rule details
console.log("Yes it is in Instance. Formatted JSON output:");
console.log(JSON.stringify(parsedResponse, null, 2));
// Show success notification
toast.current.trigger({ type: "success", content: "Rules Fetched Successfully." });
}
// Handle other non-successful status codes
else {
toast.current.trigger({ type: "error", content: "Failed to fetch rule details." });
}
} catch (error) {
// Handle any error thrown during the API call or processing
console.error("Error fetching rule details:", error);
toast.current.trigger({ type: "error", content: "Error fetching rule details." });
}
};
Summary:
The function tries to fetch rule details from an API based on given rule.id and rule.automation_type_id.
If the rule is not found (404), it shows an error toast and tries to delete the rule from a local store if possible.
If the fetch is successful, it parses the returned data, logs it, and shows a success toast.
For other errors or failed fetches, it shows error notifications appropriately.
Any unexpected errors during fetching or parsing are caught and handled gracefully.
If you'd like, I can also help you improve or refactor this function for better readability or error handling!
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 = set1;
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;
code
// 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));
return { firstRuleIds, duplicateRuleIds };
// if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
// else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
// else if (activeTab === "hourly") groups = hourlyRuleGroups;
// // exact count of items on current page
// const count = flattenGroups(groupsToShow).length;
// console.log([Pagination] Duplicate mode per-page on tab '${activeTab}' page ${pageIndex + 1}: ${count});
// return count;
// };
// 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;
const renderTimerMessage = (tabKey) => {
if (!timers[tabKey]) return null;
code
return (
<div
style={{
position: "fixed",
top: "50%",
left: "50%",
width: "60%",
transform: "translate(-75%, -50%)",
backgroundColor: "transparent",
color: "black",
zIndex: 9999,
userSelect: "none",
fontSize: "16px",
fontFamily: "sans-serif",
display: "flex",
flexDirection: "column", // Stack vertically
alignItems: "center",
whiteSpace: "normal", // allow wrapping if needed
textAlign: "center",
}}
>
<div>
The app is currently processing the data. Please refresh the page or revisit the app after (
<strong>{timers[tabKey]} sec </strong>) seconds.
</div>
<FwSpinner size="small" color="green" style={{ marginTop: "8px" }} />
</div>
);
};
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) {}
}
// Log the entity data of active tab if deleting from recent API
if (isRecentData) {
console.log(Deleting from Recent Data mode. Entity data for tab "${tabKey}":, entityDataForTab);
}
code
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) => {
// 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 Automation Type ID :", rule.display_id);
// if (response.status === 404) {
// // Show error toast
// toast.current.trigger({ type: "error", content: "Rule not found. Removing from Entity." });
// // If display_id exists and entity store reference exists
// if (rule.display_id && newRulePloadDB6.current) {
// try {
// // Delete the item from local entity store using display_id
// 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);
// }
// }
// }
const openRuleDetails = async (rule) => {
// Log the input rule details for debugging
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);
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.status);
} catch (error) {
// Handle any error thrown during the API call or processing
console.error("Error fetching rule details:", error);
// Handle case when API returns 404 (Not Found)
if (error.status === 404) {
// Show error notification to user
toast.current.trigger({ type: "error", content: "Rule not found. Removing from Entity." });
// If the rule has display_id and local entity store exists, delete the entry
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);
}
}
}
toast.current.trigger({ type: "error", content: "Error fetching rule details." }); }
// if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
// else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
// else if (activeTab === "hourly") groups = hourlyRuleGroups;
if (ruleViewFilter.value !== "duplicate_rules") {
const calculatedEnd = currentPage[activeTab] * rulesPerPage;
console.log("Non-duplicate view - Calculated End:", calculatedEnd);
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;
console.log("Initial groups (before pagination):", groups);
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 getCurrentPageItemCount = () => {
// if (ruleViewFilter.value !== "duplicate_rules") {
// return rulesPerPage;
// }
// let groups = [];
// if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
// else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
// else if (activeTab === "hourly") groups = hourlyRuleGroups;
// // Correct usage: Paginate the flattened list of items instead of the groups
// const currentPageIndex = currentPage[activeTab];
// const paginatedItems = paginateGroups(groups, rulesPerPage, currentPageIndex);
// // console.log("paginatedItems on groups :",JSON.stringify(paginatedItems,null,2))
// return paginatedItems.length; // Return the count of the items on the current page
// };
// Old
// 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;
// let totalItemCount = 0;
// for (const group of groups) {
// const filteredGroup = group.filter(
// (rule) =>
// !searchQuery.trim() ||
// rule.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
// rule.description?.toLowerCase().includes(searchQuery.toLowerCase())
// );
// totalItemCount += filteredGroup.length;
// }
// return totalItemCount;
// } else {
// return getCurrentTotalCount();
// }
// };
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;
};
newRulePloadDB6 is a ref holding the entity (local DB namespace/object) from your Freshworks client database.
When you call deleteRule, you check if the rule has a display_id and if the local entity exists in newRulePloadDB6.current.
If it does, you delete the entity record using newRulePloadDB6.current.delete(display_id).
This effectively deletes the rule locally before calling the API to delete it remotely.
So in short:
You pass the rule object to deleteRule which includes display_id.
The entity (database handle) itself is held in the React ref newRulePloadDB6.
The method newRulePloadDB6.current.delete(display_id) deletes the rule from local storage.
If you want, I can clarify further or show how to pass the entity explicitly as an argument. But from your code, the entity access is through the React ref (closure scope) — it’s not being passed as a param but accessed directly inside the function.
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.status);
} catch (error) {
// Handle any error thrown during the API call or processing
console.error("Error fetching rule details:", error);
// Handle case when API returns 404 (Not Found)
if (error.status === 404) {
// Show error notification to user
toast.current.trigger({ type: "error", content: "Rule not found. Removing from Entity." });
// If the rule has display_id and local entity store exists, delete the entry
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);
}
}
}
toast.current.trigger({ type: "error", content: "Error fetching rule details." }); }
};
then why in this it is not working
Your openRuleDetails function looks mostly fine logically, but the likely reason "it is not working" (especially the part where it deletes the rule from the local entity on 404) could be due to how the error is detected or thrown from the API call.
Common issues and things to check:
1. Is error.status === 404 actually true when API returns 404?
In many setups, the error object thrown by await client.request.invokeTemplate(...) might not have a direct status property on the error object.
The HTTP error status might be wrapped under a different property, like error.response.status or error.statusCode.
Or the error might be a JS Error without a status code and you need to parse it.
Suggestion: Log the full error object to see where the 404 status actually resides.
Modify your catch like this for debugging:
js
} catch (error) {
console.error("Error fetching rule details:", error);
// DEBUG - log full error to inspect fields
console.log("Error keys:", Object.keys(error));
// Check where status appears
const status = error.status || error.response?.status || error.statusCode || null;
console.log("Detected status:", status);
if (status === 404) {
// ...
}
}
2. Accessing and using newRulePloadDB6.current
Double-check that:
Your newRulePloadDB6.current reference is correctly initialized beforeopenRuleDetails runs.
You aren’t using a stale ref or uninitialized value (e.g., is this openRuleDetails called before initializeDatabase?).
3. Error thrown by newRulePloadDB6.current.delete()
If the delete operation itself throws, your catch inside the catch block logs the failure, so check console for errors there.
4. API response on 404 might not throw an Error
It’s possible your client.request.invokeTemplate() method:
Does not throw on 404 and instead returns a normal response with response.status === 404.
In your current version, you await and catch errors, expecting it throws, but maybe it doesn't.
If so, you want to check the response before the try-catch or inside the try after the awaited call.
Example:
js
try {
const response = await client.request.invokeTemplate("getid", {
context: {
automationid: rule.automation_type_id,
ruleid: rule.id,
},
});
if (response.status === 404) {
// handle 404 here
toast.current.trigger({ type: "error", content: "Rule not found. Removing from Entity." });
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);
}
}
return; // exit after handling 404
}
if (response.status >= 200 && response.status < 300) {
console.log("Yes it is in Instance. Formatted JSON output:");
console.log(response.status);
// proceed with success flow
} else {
toast.current.trigger({ type: "error", content: "Failed to fetch rule details." });
}
} catch (error) {
// Handle other unexpected errors
console.error("Unexpected error fetching rule details:", error);
toast.current.trigger({ type: "error", content: "Error fetching rule details." });
}
Summary:
You likely rely on the error being thrown on 404 but the API client may instead return the 404 status in response.
Check the actual shape of response and error by logging them.
Adjust your code to handle 404 based on the actual behaviour of client.request.invokeTemplate().
Ensure your local DB ref (newRulePloadDB6.current) is initialized before you use it.
Recommended quick fix:
Replace your current try-catch with something like:
js
const openRuleDetails = async (rule) => {
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);
try {
const response = await client.request.invokeTemplate("getid", {
context: {
automationid: rule.automation_type_id,
ruleid: rule.id,
},
});
if (response.status === 404) {
toast.current.trigger({ type: "error", content: "Rule not found. Removing from Entity." });
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 (delError) {
console.error("Failed to delete from entity store:", delError);
}
}
return;
}
if (response.status >= 200 && response.status < 300) {
console.log("Yes it is in Instance. Formatted JSON output:");
console.log(response);
toast.current.trigger({ type: "success", content: "Rules Fetched Successfully." });
return;
}
toast.current.trigger({ type: "error", content: "Failed to fetch rule details." });
} catch (error) {
console.error("Error fetching rule details:", error);
// fallback error handling for 404 inside catch if applicable
const status = error.status || error.response?.status || null;
if (status === 404) {
toast.current.trigger({ type: "error", content: "Rule not found. Removing from Entity." });
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 (delError) {
console.error("Failed to delete from entity store:", delError);
}
}
} else {
toast.current.trigger({ type: "error", content: "Error fetching rule details." });
}
}
};
If you want, I can also refactor or help you debug with more specific logging!
in ths, on showing active page number if user click dont allow
If I understand you correctly, you want the pagination buttons not to react or cause any action when the user clicks on the button for the current active page. In other words, clicking the currently active page number should do nothing (no page change, no state update, no reload).
How to achieve it
In your current CustomPagination component, you have the method handlePaginationClick that does this:
Currently, clicking any page number calls handlePaginationClick(page) regardless if page === currentPage or not.
Solution:
You can prevent the click handler from firing if the clicked page equals the currentPage by adding a simple condition inside handlePaginationClick:
js
const handlePaginationClick = (page) => {
if (page === currentPage) return; // Do nothing if clicked page is active page
handlePageChangeWithDelay(page);
};
With this guard, clicks on the active page number simply return early, no state updates happen.
Full snippet showing only the modified part:
js
const handlePaginationClick = (page) => {
if (page === currentPage) return; // Prevent action on clicking active page
handlePageChangeWithDelay(page);
};
Optional UX improvement: Disable pointer cursor and style active page button accordingly
You might want to visually indicate the active page number is not clickable — e.g., change cursor style and disable hover effects.
Modify your button rendering like this (inside renderPageNumbers):