-
Notifications
You must be signed in to change notification settings - Fork 251
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix: incidents refactor #1664
fix: incidents refactor #1664
Conversation
WalkthroughThis pull request introduces significant refactoring and new components across the client-side application, focusing on improving error handling, component modularity, and user interface consistency. The changes span multiple files in the Incidents, Uptime, and PageSpeed sections, introducing new custom hooks, components, and restructuring existing code to enhance flexibility and maintainability. Changes
Possibly related PRs
Suggested Reviewers
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (12)
Client/src/Pages/Incidents/index.jsx (2)
33-39
: Consider Allowing a Retry or Additional GuidanceYour fallback works wonders when the network’s dropping bombs, but you might want to add either a retry button or more detailed instructions to help the user recover gracefully. This helps keep the user from feeling like they just lost themselves in the moment.
42-60
: Enhance Loading ExperienceYou’re conditionally rendering the
IncidentTable
based onisLoading
. Consider incorporating a skeleton or a small loader to provide user feedback while data populates. This can smooth out the user experience and avoid abrupt transitions that might make the UI feel shaky, like uncertain knees.Client/src/Components/Table/skeleton.jsx (1)
3-14
: Height Adjustment Looks Good—But Verify Layout RequirementsThe change to 80% height may better align with your design aims. However, if you ever need a fully expanded skeleton down the line, keep “100%” in mind. In general, confirm the skeleton’s size meets the intended layout in diverse scenarios, so you don’t get sauce all over your perfectly set table.
Client/src/Pages/Incidents/Hooks/useMonitorsFetch.jsx (1)
4-9
: Yo, the hook setup is fire! 🔥Clean state management with well-defined initial states. Consider adding PropTypes or TypeScript for better type safety.
Client/src/Components/GenericFallback/index.jsx (1)
Line range hint
14-71
: This component's got the sauce, but we can make it even better! 🚀The implementation is solid, but consider these performance optimizations:
- Memoize the SVG components with
useMemo
since they're being conditionally rendered- Extract the static styles object to prevent recreation on each render
Here's how to optimize:
+const staticStyles = { + borderStyle: "dashed", + "& svg g g:last-of-type path": { + stroke: "inherit", + }, + position: "absolute", + top: "0", + left: "50%", + transform: "translate(-50%, -50%)", + width: "100%", + maxWidth: "800px", + height: "100%", + maxHeight: "800px", + backgroundPosition: "center", + backgroundSize: "cover", + backgroundRepeat: "no-repeat", +}; const GenericFallback = ({ children }) => { const theme = useTheme(); const mode = useSelector((state) => state.ui.mode); + + const SkeletonComponent = useMemo(() => + mode === "light" ? + <Skeleton style={{ zIndex: 1 }} /> : + <SkeletonDark style={{ zIndex: 1 }} /> + , [mode]); return ( // ... rest of the component <Box - sx={{ - "& svg g g:last-of-type path": { - // ... existing styles - }, - position: "absolute", - // ... existing styles - }} + sx={staticStyles} > - {mode === "light" ? ( - <Skeleton style={{ zIndex: 1 }} /> - ) : ( - <SkeletonDark style={{ zIndex: 1 }} /> - )} + {SkeletonComponent} </Box> // ... rest of the component ); };Client/src/Pages/Incidents/Components/IncidentTable/index.jsx (2)
57-58
: Yo dawg, let's make this status conversion more lit! 🎵Consider using a constant map for better maintainability and readability.
+const STATUS_MAP = { + true: "up", + false: "down", +}; -const status = row.status === true ? "up" : "down"; +const status = STATUS_MAP[row.status];
87-99
: Mom's spaghetti moment: Let's group these early returns! 🍝Consider grouping all early returns together for better code organization and readability.
-if (!shouldRender || isLoading) return <TableSkeleton />; - -if (networkError) { - return ( - <GenericFallback> - <NetworkError /> - </GenericFallback> - ); -} - -if (!isLoading && typeof checksCount === "undefined") { - return <GenericFallback>No incidents recorded</GenericFallback>; -} +// Handle all special cases first +if (!shouldRender || isLoading) { + return <TableSkeleton />; +} + +if (networkError) { + return ( + <GenericFallback> + <NetworkError /> + </GenericFallback> + ); +} + +if (typeof checksCount === "undefined") { + return <GenericFallback>No incidents recorded</GenericFallback>; +}Client/src/Pages/Incidents/Components/OptionsHeader/index.jsx (2)
21-21
: Let's optimize this computation with useMemo! 💪The
monitorNames
derivation could benefit from memoization to prevent unnecessary recalculations.+import { useMemo } from 'react'; + const OptionsHeader = ({ /* ... */ }) => { const theme = useTheme(); - const monitorNames = typeof monitors !== "undefined" ? Object.values(monitors) : []; + const monitorNames = useMemo(() => { + return typeof monitors !== "undefined" ? Object.values(monitors) : []; + }, [monitors]);
66-73
: DRY up these styles, they're repeating like mom's spaghetti! 🍝Extract the duplicated ButtonGroup styles into a reusable constant.
+const buttonGroupStyles = { + ml: "auto", + "& .MuiButtonBase-root, & .MuiButtonBase-root:hover": { + borderColor: theme.palette.primary.lowContrast, + }, +}; -<ButtonGroup - sx={{ - ml: "auto", - "& .MuiButtonBase-root, & .MuiButtonBase-root:hover": { - borderColor: theme.palette.primary.lowContrast, - }, - }} -> +<ButtonGroup sx={buttonGroupStyles}>Also applies to: 109-116
Client/src/Pages/Uptime/Monitors/index.jsx (1)
112-126
: Yo dawg, let's clean up this error handling! 💪The new error handling looks solid, but there's room for improvement:
- Remove that lonely space character between GenericFallback tags
- Consider extracting these messages to translation files for i18n support
- Consider moving the spacing value (4) to a constants file for consistency
Here's how to drop these bars:
if (networkError) { return ( <GenericFallback> - {" "} <Typography variant="h1" - marginY={theme.spacing(4)} + marginY={theme.spacing(SPACING_LARGE)} color={theme.palette.primary.contrastTextTertiary} > - Network error + {t('errors.network.title')} </Typography> - <Typography>Please check your connection</Typography> + <Typography>{t('errors.network.message')}</Typography> </GenericFallback> ); }Add to your constants file:
export const SPACING_LARGE = 4;Client/src/Pages/Incidents/Hooks/useChecksFetch.jsx (1)
10-13
: Yo dawg, consider using a single state object for related statesThese states are tightly coupled and could be managed together. Combining them would reduce the number of state updates and prevent potential race conditions.
-const [isLoading, setIsLoading] = useState(false); -const [networkError, setNetworkError] = useState(false); -const [checks, setChecks] = useState(undefined); -const [checksCount, setChecksCount] = useState(undefined); +const [state, setState] = useState({ + isLoading: false, + networkError: false, + checks: undefined, + checksCount: undefined +});Client/src/Pages/PageSpeed/Monitors/index.jsx (1)
30-41
: Let's make this error message more accessible, yo!Consider adding aria-live region for screen readers to announce network errors.
<GenericFallback> <Typography variant="h1" marginY={theme.spacing(4)} color={theme.palette.primary.contrastTextTertiary} + role="alert" + aria-live="polite" > Network error </Typography> - <Typography>Please check your connection</Typography> + <Typography role="status">Please check your connection</Typography> </GenericFallback>
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (19)
Client/src/Components/GenericFallback/NetworkError.jsx
(1 hunks)Client/src/Components/GenericFallback/index.jsx
(3 hunks)Client/src/Components/Table/TablePagination/index.jsx
(1 hunks)Client/src/Components/Table/skeleton.jsx
(1 hunks)Client/src/Pages/Incidents/Components/IncidentTable/index.jsx
(1 hunks)Client/src/Pages/Incidents/Components/OptionsHeader/index.jsx
(1 hunks)Client/src/Pages/Incidents/Components/OptionsHeader/skeleton.jsx
(1 hunks)Client/src/Pages/Incidents/Hooks/useChecksFetch.jsx
(1 hunks)Client/src/Pages/Incidents/Hooks/useMonitorsFetch.jsx
(1 hunks)Client/src/Pages/Incidents/IncidentTable/Empty/Empty.jsx
(0 hunks)Client/src/Pages/Incidents/IncidentTable/Skeleton/Skeleton.jsx
(0 hunks)Client/src/Pages/Incidents/IncidentTable/index.jsx
(0 hunks)Client/src/Pages/Incidents/index.jsx
(1 hunks)Client/src/Pages/Incidents/skeleton.jsx
(0 hunks)Client/src/Pages/PageSpeed/Monitors/index.jsx
(3 hunks)Client/src/Pages/Uptime/Monitors/Components/UptimeDataTable/index.jsx
(2 hunks)Client/src/Pages/Uptime/Monitors/index.jsx
(2 hunks)Client/src/Routes/index.jsx
(1 hunks)Client/src/Utils/NetworkService.js
(0 hunks)
💤 Files with no reviewable changes (5)
- Client/src/Pages/Incidents/IncidentTable/Skeleton/Skeleton.jsx
- Client/src/Utils/NetworkService.js
- Client/src/Pages/Incidents/skeleton.jsx
- Client/src/Pages/Incidents/IncidentTable/Empty/Empty.jsx
- Client/src/Pages/Incidents/IncidentTable/index.jsx
✅ Files skipped from review due to trivial changes (2)
- Client/src/Pages/Incidents/Components/OptionsHeader/skeleton.jsx
- Client/src/Pages/Uptime/Monitors/Components/UptimeDataTable/index.jsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (13)
Client/src/Pages/Incidents/index.jsx (2)
1-13
: Nicely Structured ImportsReally digging how you have grouped your imports in a clear, modular manner here—no signs of sweaty palms in this segment, mate. This approach effectively reveals project dependencies at a glance and eases navigation for future maintainers. Keep it up, no spaghetti spilled.
18-19
: Validate the User Object Before Using Its PropertiesWhile referencing
user.teamId
, ensure thatuser
is consistently defined to sidestep potential runtime errors. Ifuser
might ever be null or undefined, you might want to add a guard check or a fallback.Client/src/Components/GenericFallback/NetworkError.jsx (1)
1-20
: Solid and Straightforward Network Error ComponentGreat job abstracting out the
NetworkError
. Its simplicity is fresh and keeps the application clear of messy code. For event completeness, consider adding a retry action or more contextual info (like error codes), so users can try again without needing to drop their own spaghetti.Client/src/Pages/Incidents/Hooks/useMonitorsFetch.jsx (1)
48-51
: Clean exports, my G! 💯The return values and exports are well-structured and provide all necessary states.
Client/src/Pages/Incidents/Components/IncidentTable/index.jsx (2)
1-37
: Yo, this component structure is fire! 🔥Clean separation of concerns with custom hooks for data fetching and local state for pagination. Props to you for following React best practices!
101-126
: Clean render logic, straight fire! 🎤Well-structured JSX and proper prop types validation. Keep it up!
Client/src/Components/Table/TablePagination/index.jsx (1)
11-11
: Props flexibility upgrade, nice! 🎵Making
rowsPerPage
optional with a default value of 5 is a solid improvement for component reusability.Client/src/Routes/index.jsx (1)
31-33
: New routes looking clean, no cap! 🎯The Status and Integrations routes are properly integrated into the existing structure under the protected route.
Client/src/Pages/Uptime/Monitors/index.jsx (1)
9-9
: Yo, these import changes are straight fire! 🔥The addition of GenericFallback and Typography components shows you're keeping it real with better error handling and UI consistency.
Also applies to: 15-15
Client/src/Pages/Incidents/Hooks/useChecksFetch.jsx (3)
15-20
: Clean setup of async data fetching! 🍝Good practice setting loading state before the fetch operation.
48-60
: Error handling's looking fresh! 🔥Solid error handling with toast notifications and proper cleanup in the finally block. Dependencies array is on point too!
21-48
: Mom's spaghetti moment: Let's clean up this API call duplicationThe parameter objects for both API calls are nearly identical. We could reduce duplication and improve maintainability.
+const getBaseParams = () => ({ + authToken, + status: false, + sortOrder: "desc", + limit: null, + dateRange, + filter, + page, + rowsPerPage, +}); if (selectedMonitor === "0") { - res = await networkService.getChecksByTeam({ - authToken: authToken, - status: false, - teamId: user.teamId, - sortOrder: "desc", - limit: null, - dateRange, - filter: filter, - page: page, - rowsPerPage: rowsPerPage, - }); + res = await networkService.getChecksByTeam({ + ...getBaseParams(), + teamId: user.teamId, + }); } else { - res = await networkService.getChecksByMonitor({ - authToken: authToken, - status: false, - monitorId: selectedMonitor, - sortOrder: "desc", - limit: null, - dateRange, - filter: filter, - page, - rowsPerPage, - }); + res = await networkService.getChecksByMonitor({ + ...getBaseParams(), + monitorId: selectedMonitor, + }); }Also, consider adding response data validation to prevent runtime errors.
✅ Verification successful
Yo, the spaghetti's only in one spot, dawg!
The refactoring suggestion is solid for the Incidents hook, but the other file using these API calls has a clean, focused implementation. Keep the refactor local to
Client/src/Pages/Incidents/Hooks/useChecksFetch.jsx
.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for similar API call patterns that could benefit from this refactor rg -l 'networkService\.(getChecksByTeam|getChecksByMonitor)' --type jsLength of output: 181
Script:
#!/bin/bash # Check the implementation in the Uptime Details hook cat Client/src/Pages/Uptime/Details/Hooks/useChecksFetch.jsxLength of output: 1210
Client/src/Pages/PageSpeed/Monitors/index.jsx (1)
Line range hint
3-14
: Imports looking clean as mom's spaghetti! 🍝Good organization of imports with clear categorization using comments.
useEffect(() => { | ||
const fetchMonitors = async () => { | ||
try { | ||
setIsLoading(true); | ||
const res = await networkService.getMonitorsByTeamId({ | ||
authToken, | ||
teamId, | ||
limit: null, | ||
types: null, | ||
status: null, | ||
checkOrder: null, | ||
normalize: null, | ||
page: null, | ||
rowsPerPage: null, | ||
filter: null, | ||
field: null, | ||
order: null, | ||
}); | ||
if (res?.data?.data?.monitors?.length > 0) { | ||
const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => { | ||
acc[monitor._id] = monitor; | ||
return acc; | ||
}, {}); | ||
setMonitors(monitorLookup); | ||
} | ||
} catch (error) { | ||
setNetworkError(true); | ||
createToast({ | ||
body: error.message, | ||
}); | ||
} finally { | ||
setIsLoading(false); | ||
} | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bruh, we got some spaghetti code here that needs cleanup! 🍝
Several issues need attention:
- Missing cleanup function could cause memory leaks if component unmounts during fetch
- Deep nested response access
res?.data?.data?.monitors?.length
needs better error handling - All null parameters could be simplified
Here's how to fix these issues:
useEffect(() => {
+ let isSubscribed = true;
const fetchMonitors = async () => {
try {
setIsLoading(true);
const res = await networkService.getMonitorsByTeamId({
authToken,
teamId,
- limit: null,
- types: null,
- status: null,
- checkOrder: null,
- normalize: null,
- page: null,
- rowsPerPage: null,
- filter: null,
- field: null,
- order: null,
});
- if (res?.data?.data?.monitors?.length > 0) {
+ if (!isSubscribed) return;
+ const monitors = res?.data?.data?.monitors;
+ if (Array.isArray(monitors) && monitors.length > 0) {
const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => {
acc[monitor._id] = monitor;
return acc;
}, {});
setMonitors(monitorLookup);
}
} catch (error) {
+ if (!isSubscribed) return;
setNetworkError(true);
createToast({
body: error.message,
});
} finally {
+ if (!isSubscribed) return;
setIsLoading(false);
}
};
fetchMonitors();
+ return () => {
+ isSubscribed = false;
+ };
}, [authToken, teamId]);
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
useEffect(() => { | |
const fetchMonitors = async () => { | |
try { | |
setIsLoading(true); | |
const res = await networkService.getMonitorsByTeamId({ | |
authToken, | |
teamId, | |
limit: null, | |
types: null, | |
status: null, | |
checkOrder: null, | |
normalize: null, | |
page: null, | |
rowsPerPage: null, | |
filter: null, | |
field: null, | |
order: null, | |
}); | |
if (res?.data?.data?.monitors?.length > 0) { | |
const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => { | |
acc[monitor._id] = monitor; | |
return acc; | |
}, {}); | |
setMonitors(monitorLookup); | |
} | |
} catch (error) { | |
setNetworkError(true); | |
createToast({ | |
body: error.message, | |
}); | |
} finally { | |
setIsLoading(false); | |
} | |
}; | |
useEffect(() => { | |
let isSubscribed = true; | |
const fetchMonitors = async () => { | |
try { | |
setIsLoading(true); | |
const res = await networkService.getMonitorsByTeamId({ | |
authToken, | |
teamId, | |
}); | |
if (!isSubscribed) return; | |
const monitors = res?.data?.data?.monitors; | |
if (Array.isArray(monitors) && monitors.length > 0) { | |
const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => { | |
acc[monitor._id] = monitor; | |
return acc; | |
}, {}); | |
setMonitors(monitorLookup); | |
} | |
} catch (error) { | |
if (!isSubscribed) return; | |
setNetworkError(true); | |
createToast({ | |
body: error.message, | |
}); | |
} finally { | |
if (!isSubscribed) return; | |
setIsLoading(false); | |
} | |
}; | |
fetchMonitors(); | |
return () => { | |
isSubscribed = false; | |
}; | |
}, [authToken, teamId]); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Auto Pull Request Review from LlamaPReview
Large PR Notification
Dear contributor,
Thank you for your substantial contribution to this project. LlamaPReview has detected that this Pull Request contains a large volume of changes, which exceeds our current processing capacity.
Details:
- PR and related contents total size: Approximately 53,619 characters
- Current limit: 50,000 characters
Next steps:
- Consider breaking this PR into smaller, more focused changes if possible.
- For manual review, please reach out to your team members or maintainers.
We appreciate your understanding and commitment to improving this project. Your contributions are valuable, and we want to ensure they receive the attention they deserve.
LlamaPReview is continuously evolving to better serve the community. Share your thoughts on handling large PRs in our GitHub Discussions - your feedback helps us improve and expand our capabilities.
If you have any questions or need assistance, our community and support team are here to help.
Best regards,
LlamaPReview Team
This PR refactors the incidents page for correctness, stability, and readability.