On initial load, fetches entity data for the active tab (default "ticketcreate").
On tab change, fetches entity data if in entity mode or fetches API data if in API mode.
When user clicks the toggle button:
If currently in entity mode, fetches API data and switches to API mode.
If currently in API mode, fetches entity data and switches to entity mode.
The button text toggles between "Recent API Data" and "Get Entity Data".
Pagination, search, grouping, deleting and other existing functionalities remain intact.
add this functionality, dont remove anything from my code
give me complete component
Assistant
Certainly! I've added the requested functionality:
On initial load, the component already fetches entity data (Filterrecords) since fetchFromApi starts as true but inside fetchData, if fetchFromApi is true it calls the API fetchers (getTicketCreationRules etc.), if false calls entity. So I flipped the initial state of fetchFromApi to false so initial load fetches entity data (not API).
On tab change, a useEffect triggers fetchData to fetch data for that tab depending on fetchFromApi.
The toggle button calls fetchData and toggles mode and button text accordingly.
Pagination, grouping, search etc remain intact.
No code removed, just added the required useEffect and adjusted initial state and minor fixes to make toggle behavior on tab change working smoothly.
Here is the complete component with these changes implemented and detailed comments where logic is added/updated:
jsx
User
in this code, this functionality is missing, what tab is active it should call that tab (api or entity)
Assistant
Thanks for pointing that out! You want the toggle button to fetch data only for the currently active tab (and from the proper source API or Entity DB), not for all tabs every time it toggles. The current code fetches all three tabs' data every time.
How to fix:
We should update the fetch logic inside the useEffect that listens on activeTab or fetchFromApi to fetch data only for the active tab (instead of all tabs at once), whether from API or entity DB.
The same applies to the toggle button — we keep toggling fetchFromApi, and the useEffect fetches only relevant data for the current active tab based on the toggle.
Here’s the updated useEffect and related adjustments to fetch data only for the active tab:
js
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
if (fetchFromApi) {
try {
if (activeTab === "ticketcreate") {
const data = await getTicketCreationRules(client);
setTicketCreationRules(data);
} else if (activeTab === "ticketupdate") {
const data = await getTicketUpdationRules(client);
setTicketUpdateRules(data);
} else if (activeTab === "hourly") {
const data = await getHourlyRules(client);
setHourlyTriggerRules(data);
}
const agentData = await getAgents(client);
setAgent(agentData);
} catch (err) {
console.error("Error fetching API data:", err);
}
} else {
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
try {
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);
}
} catch (err) {
console.error("Error fetching entity data:", err);
}
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
User
rror in getting Ticket Creation rules: TypeError: setState is not a function
at _callee5 @ common.js:169
tryCatch @ common.js:2
(anonymous) @ common.js:2
(anonymous) @ common.js:2
asyncGeneratorStep @ common.js:2
_next @ common.js:2
Promise.then
asyncGeneratorStep @ common.js:2
_next @ common.js:2
(anonymous) @ common.js:2
(anonymous) @ common.js:2
_getTicketCreationRules @ common.js:171
getTicketCreationRules @ common.js:162
_callee31 @ react-dom.development.js:11276
flushPassiveEffects @ react-dom.development.js:23447
flushDiscreteUpdates @ react-dom.development.js:22356
flushDiscreteUpdatesIfNeeded @ react-dom.development.js:3768
dispatchDiscreteEvent @ react-dom.development.js:5886Understand this error
common.js:176 Uncaught TypeError: Cannot read properties of undefined (reading 'filter')
at pagination (common.js:176:17)
at getPaginatedItemCount (AutomationTabs.js:697:35)
at AutomationTabs (AutomationTabs.js:792:34)
at renderWithHooks (react-dom.development.js:14985:1)
at updateFunctionComponent (react-dom.development.js:17356:1)
at beginWork (react-dom.development.js:19063: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
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
runWithPriority @ AutomationTabs.js:207
tryCatch @ AutomationTabs.js:2
(anonymous) @ AutomationTabs.js:2
(anonymous) @ AutomationTabs.js:2
asyncGeneratorStep @ AutomationTabs.js:2
_next @ AutomationTabs.js:2
Promise.then
asyncGeneratorStep @ AutomationTabs.js:2
_next @ AutomationTabs.js:2
(anonymous) @ AutomationTabs.js:2
(anonymous) @ AutomationTabs.js:2
fetchOnTabOrModeChange @ AutomationTabs.js:201
(anonymous) @ AutomationTabs.js:246
invokePassiveEffectCreate @ react-dom.development.js:23487
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
flushPassiveEffectsImpl @ react-dom.development.js:23574
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority$1 @ react-dom.development.js:11276
flushPassiveEffects @ react-dom.development.js:23447
flushDiscreteUpdates @ react-dom.development.js:22356
flushDiscreteUpdatesIfNeeded @ react-dom.development.js:3768
dispatchDiscreteEvent @ react-dom.development.js:5886Understand this error
AutomationTabs.js:207 The above error occurred in the component:
Assistant
Let's analyze the errors you are encountering step-by-step to understand their root causes.
Error 1
code
TypeError: setState is not a function
at _callee5$ (common.js:166:7)
This error means somewhere in your code you are passing something that is not a function as the setState callback to one of your async methods, or your getTicketCreationRules (or similar) function is invoked with an argument which is expected to be a setter setState function but isn't.
Why does this happen?
Looking at your usage in the earlier code snippet, you have this pattern:
But from the error, looks like your getTicketCreationRules or similar functions in common.js expect a setter function as a parameter; and use it internally like:
js
async function getTicketCreationRules(client, setState) {
// ...
setState(rules); // or similar
}
If instead, in the updated code you do:
js
const data = await getTicketCreationRules(client);
setTicketCreationRules(data);
But your getTicketCreationRules is internally expecting a callback, omitting the callback will cause setState inside the function to be undefined which causes an error: setState is not a function.
Error 2
code
TypeError: Cannot read properties of undefined (reading 'filter')
at pagination (common.js:176)
Your pagination function is trying to filter an undefined object. This usually happens because the rules array passed to pagination is undefined.
Typical reasons for this:
Your state variable (like ticketCreationRules) is undefined or is set to undefined somewhere.
User
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
if (fetchFromApi) {
// Fetch from API
try {
await Promise.all([
getAgents(client, (data) => {
setAgent(data);
}),
getTicketCreationRules(client, (data) => {
setTicketCreationRules(data);
}),
getTicketUpdationRules(client, (data) => {
setTicketUpdateRules(data);
}),
getHourlyRules(client, (data) => {
setHourlyTriggerRules(data);
})
]);
} catch (err) {
console.error("Error fetching API data:", err);
}
} else {
// Fetch from Entity DB
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
code
try {
const entticketcreate = await Filterrecords(ticketCreate, newRulePloadDB5.current);
const enthourly = await Filterrecords(hourlyTriggers, newRulePloadDB5.current);
const entticketupdate = await Filterrecords(ticketUpdate, newRulePloadDB5.current);
setTicketCreationRules(entticketcreate);
setTicketUpdateRules(entticketupdate);
setHourlyTriggerRules(enthourly);
} catch (err) {
console.error("Error fetching entity data:", err);
}
}
setLoading(false);
};
// Only fetch if tabs have initialized and rules DB is ready
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
in below code this is handled perfectly please check how and modify your given code
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
if (fetchFromApi) {
try {
if (activeTab === "ticketcreate") {
const data = await getTicketCreationRules(client);
setTicketCreationRules(data);
} else if (activeTab === "ticketupdate") {
const data = await getTicketUpdationRules(client);
setTicketUpdateRules(data);
} else if (activeTab === "hourly") {
const data = await getHourlyRules(client);
setHourlyTriggerRules(data);
}
const agentData = await getAgents(client);
setAgent(agentData);
} catch (err) {
console.error("Error fetching API data:", err);
}
} else {
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
code
Assistant
Great observation!
The key difference between the two snippets you shared is how the helper functions (getTicketCreationRules, getAgents, etc.) are invoked:
In your first snippet, you pass a callback (data) => setState(data) to each function and use Promise.all to run all requests in parallel.
In the second snippet, you await each fetch sequentially, expecting these functions to return the data rather than accept a callback, and then immediately set state after.
Both are valid patterns, but they depend on how your helper functions are implemented.
Why your second snippet is “handling agent fetch perfectly”:
Because it calls await getAgents(client) and expects getAgents to return the data directly.
Then setAgent(agentData) sets the agent state after the awaited call.
Your first snippet passes a callback to the helpers, which means those helpers expect a callback to set state themselves internally.
To fix and unify your code:
You must be consistent with how the helper functions (getTicketCreationRules, getAgents, etc.) are implemented.
If your helpers are implemented like this:
js
// expects a callback that it calls internally after fetching data
async function getTicketCreationRules(client, setRules) {
const data = await ...; // fetch
setRules(data);
}
Then your first snippet using Promise.all([getTicketCreationRules(client, setTicketCreationRules), ...])is valid.
In this case, getAgents must also accept a callback:
js
async function getAgents(client, setAgent) {
const data = await ...;
setAgent(data);
}
And your call should be:
js
User
give me the fixed snippet
Assistant
Certainly! Here's the fixed useEffect snippet that assumes your helper functions return data (instead of accepting a setter callback), including getAgents. This matches your preferred pattern with sequential awaits for only the active tab and agent fetch:
jsx
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
if (fetchFromApi) {
try {
if (activeTab === "ticketcreate") {
const data = await getTicketCreationRules(client);
setTicketCreationRules(data);
} else if (activeTab === "ticketupdate") {
const data = await getTicketUpdationRules(client);
setTicketUpdateRules(data);
} else if (activeTab === "hourly") {
const data = await getHourlyRules(client);
setHourlyTriggerRules(data);
}
const agentData = await getAgents(client);
setAgent(agentData);
} catch (err) {
console.error("Error fetching API data:", err);
}
} else {
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
try {
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);
}
} catch (err) {
console.error("Error fetching entity data:", err);
}
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
Notes:
This snippet fetches only the currently active tab data (API or entity mode) plus agents.
Your helper functions (getTicketCreationRules, getAgents, etc.) must be async and return the data, for example:
js
export async function getTicketCreationRules(client) {
//...fetch logic
return fetchedRulesArray;
}
Let me know if you want me to help verify or refactor your helper functions accordingly!
User
common.js:169 Error in getting Ticket Creation rules: TypeError: setState is not a function
at _callee5$ (common.js:166:7)
at tryCatch (common.js:2:1)
at Generator. (common.js:2:1)
at Generator.next (common.js:2:1)
at asyncGeneratorStep (common.js:2:1)
at _next (common.js:2:1)
common.js:176 Uncaught TypeError: Cannot read properties of undefined (reading 'filter')
at pagination (common.js:176:17)
at getPaginatedItemCount (AutomationTabs.js:697:35)
at AutomationTabs (AutomationTabs.js:792:34)
AutomationTabs.js:207 The above error occurred in the component:
code
at AutomationTabs (http://localhost:10001/iframe/agent/scripts/main.f9af4c7e.js:936:22)
at App (http://localhost:10001/iframe/agent/scripts/main.f9af4c7e.js:51:21)
at Root (http://localhost:10001/iframe/agent/scripts/main.f9af4c7e.js:2170: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.
AutomationTabs.js:218 Error fetching API data: TypeError: Cannot read properties of undefined (reading 'filter')
at pagination (common.js:176:17)
at getPaginatedItemCount (AutomationTabs.js:697:35)
at AutomationTabs (AutomationTabs.js:792:34)
why this error occurs?
Assistant
Let's break down your errors one by one and understand the root causes and fixes.
1. TypeError: setState is not a function in common.js
Meaning:
This error indicates that inside your getTicketCreationRules (and probably other similar helper functions), you are using a variable named setState (or any parameter used for updating React state), expecting it to be a function, but it's actually undefined or something else.
Why does this happen?
Your getTicketCreationRules helper is expecting a callback function to update the state, i.e., it looks like this:
js
export async function getTicketCreationRules(client, setState) {
const data = await ... // fetch or API call
setState(data); // assumes setState is a function
}
But in your React component, you are calling getTicketCreationRules(client) WITHOUT passing the setter function.
How to fix?
You have two possible approaches, but choose only one to be consistent.
Option A - Pass a setter callback to all these helpers
Changed initial state of fetchFromApi to false so initial load fetches Entity Data.
Added a useEffect hooked to both activeTab and fetchFromApi to fetch relevant data whenever the tab or mode changes.
Modified fetchData function to just toggle fetchFromApi state. The actual fetching happens automatically in the above effect.
Updated toggle button text to show "Recent API Data" or "Get Entity Data" depending on current mode (fetchFromApi boolean).
Maintained all other functionalities and code intact.
This will meet your requirements while keeping the integrity of your existing code. Let me know if you want me to help with anything else!
Explanation:
When activeTab or fetchFromApi changes, fetch data only for the specific tab.
Also fetch agents every time from API (or optionally you can do this only once or on demand).
This reduces unnecessary fetches and keeps your UI consistent with the active tab.
Complete minimal snippet that you should replace for fetching in your current component:
Replace the original useEffect that fetches on [activeTab, fetchFromApi, ...] with the snippet above.
Bonus: If you want the toggle button text to say "Recent API Data" when showing entity data and "Get Entity Data" when showing API data, you may want to flip labels or clarify them, but I kept your existing text consistent.
If you want me to provide you with a full updated component incorporating only this fix or any other help, just ask!
at AutomationTabs (http://localhost:10001/iframe/agent/scripts/main.f9af4c7e.js:936:22)
at App (http://localhost:10001/iframe/agent/scripts/main.f9af4c7e.js:51:21)
at Root (http://localhost:10001/iframe/agent/scripts/main.f9af4c7e.js:2170: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:11276commitRoot@react−dom.devel1 @ react-dom.development.js:11276
flushSyncCallbackQueueImpl @ react-dom.development.js:11322
flushSyncCallbackQueue @ react-dom.development.js:11309
scheduleUpdateOnFiber @ react-dom.development.js:21893
dispatchAction @ react-dom.development.js:16139
_callee31 @ react-dom.development.js:11276
flushPassiveEffects @ react-dom.development.js:23447
flushDiscreteUpdates @ react-dom.development.js:22356
flushDiscreteUpdatesIfNeeded @ react-dom.development.js:3768
dispatchDiscreteEvent @ react-dom.development.js:5886Understand this error
AutomationTabs.js:218 Error fetching API data: TypeError: Cannot read properties of undefined (reading 'filter')
at pagination (common.js:176:17)
at getPaginatedItemCount (AutomationTabs.js:697:35)
at AutomationTabs (AutomationTabs.js:792:34)
at renderWithHooks (react-dom.development.js:14985:1)
at updateFunctionComponent (react-dom.development.js:17356:1)
at beginWork (react-dom.development.js:19063: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 @ AutomationTabs.js:218
tryCatch @ AutomationTabs.js:2
(anonymous) @ AutomationTabs.js:2
(anonymous) @ AutomationTabs.js:2
asyncGeneratorStep @ AutomationTabs.js:2
_next @ AutomationTabs.js:2
Promise.then
asyncGeneratorStep @ AutomationTabs.js:2
_next @ AutomationTabs.js:2
(anonymous) @ AutomationTabs.js:2
(anonymous) @ AutomationTabs.js:2
fetchOnTabOrModeChange @ AutomationTabs.js:201
(anonymous) @ AutomationTabs.js:246
invokePassiveEffectCreate @ react-dom.development.js:23487
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
flushPassiveEffectsImpl @ react-dom.development.js:23574
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority$1 @ react-dom.development.js:11276
flushPassiveEffects @ react-dom.development.js:23447
flushDiscreteUpdates @ react-dom.development.js:22356
flushDiscreteUpdatesIfNeeded @ react-dom.development.js:3768
dispatchDiscreteEvent @ react-dom.development.js:5886Understand this error
heap.js:2
code
POST
why this error occurs?
Your getTicketCreationRules returns undefined or your logic didn't assign state properly.
Your code calls pagination() on some data before it's properly loaded.
How to Fix Both Issues
1. Fix the getTicketCreationRules / getTicketUpdationRules / getHourlyRules invocation:
From the first error, you must call those functions with a setter callback (as your original code did) or rewrite those functions to return data properly.
E.g. If your functions expect a callback, continue passing a setter function and do NOT expect a return value:
const data = await getTicketCreationRules(client);
setTicketCreationRules(data); // This will cause the "setState is not a function" error if getTicketCreationRules expects a callback
5. Adjust your useEffect fetch code accordingly
js
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
if (fetchFromApi) {
try {
if (activeTab === "ticketcreate") {
await getTicketCreationRules(client, setTicketCreationRules);
} else if (activeTab === "ticketupdate") {
await getTicketUpdationRules(client, setTicketUpdateRules);
} else if (activeTab === "hourly") {
await getHourlyRules(client, setHourlyTriggerRules);
}
const agentData = await getAgents(client);
setAgent(agentData);
} catch (err) {
console.error("Error fetching API data:", err);
}
} else {
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
try {
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);
}
} catch (err) {
console.error("Error fetching entity data:", err);
}
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
Summary
Check your imported getTicketCreationRules etc. functions to determine whether they expect a setter callback (the original style) or return data (the new style).
Call them accordingly — you can't mix styles.
Add defensive checks in all filtering and pagination functions that receive these states to ensure no undefined input.
Initialize states with empty arrays (useState([])), which you already do.
If you want, I can help you refactor your helper functions (getTicketCreationRules, etc.) to return promises with data instead of callback setters for a cleaner usage.
If you want me to check your helper common.js methods for proper async usage and rewrite as needed, please share those functions.
Let me know if you want me to guide you through those changes or provide the fixed full component code with properly handled async calls!
try {
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);
}
} catch (err) {
console.error("Error fetching entity data:", err);
}
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
If you want, I can help you refactor all helpers to consistently return data. Just share or confirm how getTicketCreationRules and others are currently implemented.
Option B - Refactor your helper functions to return data and call setState yourself
This is usually cleaner and more idiomatic:
js
const data = await getTicketCreationRules(client);
setTicketCreationRules(data);
Your helper should look like:
js
export async function getTicketCreationRules(client) {
const response = await client.request.invokeTemplate(/*...*/);
// process response
return response.records || []; // return data, no setter inside
}
You currently seem to have a mismatch: your helpers expect setters but you call them as if they return promises with data. The easiest fix is to unify to Option A or Option B consistently.
2. TypeError: Cannot read properties of undefined (reading 'filter') in pagination
This happens because somewhere your component is calling pagination or .filter() on undefined.
Most likely cause:
Your state variables like ticketCreationRules are undefined at some point during render.
Your getTicketCreationRules or other fetch functions failed to set state correctly, or the value set was undefined.
pagination expects an array, but gets undefined or null.
How to fix:
Make sure all your states are initialized as empty arrays in useState([]).
e.g.,
Make sure your filtering functions check for array validity before filtering:
js
const getFilteredRules = (rules) => {
if (!Array.isArray(rules)) return [];
if (!searchQuery.trim()) return rules;
return rules.filter(...);
};
Ensure your helper functions return arrays or you only set state if valid data is received.
Summary / Recommendations
Pick and stick to one style for your helper functions:
Either pass setter callbacks to them (modify your useEffect accordingly).
Or make them pure async functions returning data, and in your useEffect set the state yourself.
Protect your code against undefined data:
Initialize states as empty arrays.
Validate data before running .filter() or other array methods.
Example of corrected useEffect assuming Option A (helpers expect setter callbacks):
js
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
if (fetchFromApi) {
try {
if (activeTab === "ticketcreate") {
await getTicketCreationRules(client, setTicketCreationRules);
} else if (activeTab === "ticketupdate") {
await getTicketUpdationRules(client, setTicketUpdateRules);
} else if (activeTab === "hourly") {
await getHourlyRules(client, setHourlyTriggerRules);
}
await getAgents(client, setAgent);
} catch (err) {
console.error("Error fetching API data:", err);
}
} else {
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
try {
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);
}
} catch (err) {
console.error("Error fetching entity data:", err);
}
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
Or
If you want Option B (pure async returning data), refactor your helpers accordingly and use:
js
const data = await getTicketCreationRules(client);
setTicketCreationRules(data);
etc.
Additional tip:
Add defensive guards inside your pagination and filtering functions, for example:
js
const pagination = (items, page) => {
if (!Array.isArray(items)) return [];
// ... rest of pagination code
};
If you want me to help refactor your helpers or give you a full working example with either approach, please share your getTicketCreationRules (and similar) helper code. That will help me give exact fixes!
In short: the setState is not a function error is caused by calling your helpers inconsistently with their signature. The filter error occurs because your states are undefined or not arrays at some point due to that. Fix the first and the second will go away.
Let me know if you want me to generate a full corrected component snippet once you confirm your helper function style.