My stack is: React (NextJs), Recoil, React Query
I am struggling to make sense of a bug in my code. The following HOC uses React-Query to get some data from the Db.
const NotificationsWrapper: FC = () => {
const [resData, resMeta] = useQuery(getTeamEvents, null, {
refetchInterval: 180000, // 3min
refetchIntervalInBackground: true,
refetchOnWindowFocus: false,
retry: 3,
retryDelay: 1000 * 60 * 15,
});
if (resMeta.isSuccess) {
return <Notifications data={resData} />;
} else {
return <p>Failed to fetch notifications. Please try again later!</p>;
}
};
The Notifications component uses useEffect to organise the data & push it to the recoil state for notifications & few others. This component is a bit messy & long hence not being included here.
Somewhere else in my app, I have a component called TeamMsgs which, once opened, uses useEffect to update notifications state based on a specific criteria.
This is where things are going wrong. When I open TeamMsgs component, the app falls into infinite loop.
I dont understand why this is so. The console.logs show the TeamMsgs component updating the notifications recoil state, however, then the Notifications component is triggered again and it appears to over-write the notifications state with (now) obsolete data (that it received from the HOC).
Troubleshooting: I could not understand why so I used some dummy data within the HOC NotificationsWrapper, simply as such:
const NotificationsWrapper: FC = () => {
const [resData, resMeta] = useQuery(getTeamEvents, null, {
refetchInterval: 180000, // 3min
refetchIntervalInBackground: true,
refetchOnWindowFocus: false,
retry: 3,
retryDelay: 1000 * 60 * 15,
});
if (resMeta.isSuccess) {
return <Notifications data={dummyData} />;
// return <Notifications data={resData} />; // server data not used
} else {
return <p>Failed to fetch notifications. Please try again later!</p>;
}
};
This works fine.
I have two questions:
1 - How to debug this further. I tried using useMemo & useCallback within Notifications component, without any benefit.
2 - What is causing this infinite loop where the Notifications component useEffect is updating the state after TeamMsgs component updates the state. I can confirm that the HOC is not calling the query func within the infinite loop.