Skip to content
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

Merged
merged 5 commits into from
Jan 30, 2025
Merged

fix: incidents refactor #1664

merged 5 commits into from
Jan 30, 2025

Conversation

ajhollid
Copy link
Collaborator

This PR refactors the incidents page for correctness, stability, and readability.

  • Extract network operations to hooks
  • Add consistent loading states
  • Use standard intiialziation states
  • Add skeleton components

Copy link

coderabbitai bot commented Jan 29, 2025

Walkthrough

This 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

File Path Change Summary
Client/src/Components/GenericFallback/NetworkError.jsx New NetworkError component for displaying network error messages
Client/src/Components/GenericFallback/index.jsx Renamed NetworkErrorFallback to GenericFallback, made more flexible with children prop
Client/src/Components/Table/TablePagination/index.jsx Made rowsPerPage prop optional with default value of 5
Client/src/Components/Table/skeleton.jsx Renamed UptimeDataTableSkeleton to TableSkeleton
Client/src/Pages/Incidents/* Major refactoring of Incidents page components, added new hooks and components
Client/src/Routes/index.jsx Added new routes for Status and Integrations
Client/src/Utils/NetworkService.js Removed limit parameter from getMonitorsByTeamId method

Possibly related PRs

Suggested Reviewers

  • marcelluscaio
  • jennifer-gan
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a 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 Guidance

Your 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 Experience

You’re conditionally rendering the IncidentTable based on isLoading. 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 Requirements

The 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:

  1. Memoize the SVG components with useMemo since they're being conditionally rendered
  2. 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:

  1. Remove that lonely space character between GenericFallback tags
  2. Consider extracting these messages to translation files for i18n support
  3. 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 states

These 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9c04ecd and 02d93fd.

📒 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 Imports

Really 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 Properties

While referencing user.teamId, ensure that user is consistently defined to sidestep potential runtime errors. If user 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 Component

Great 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 duplication

The 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 js

Length of output: 181


Script:

#!/bin/bash
# Check the implementation in the Uptime Details hook
cat Client/src/Pages/Uptime/Details/Hooks/useChecksFetch.jsx

Length 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.

Comment on lines +11 to +44
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);
}
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Bruh, we got some spaghetti code here that needs cleanup! 🍝

Several issues need attention:

  1. Missing cleanup function could cause memory leaks if component unmounts during fetch
  2. Deep nested response access res?.data?.data?.monitors?.length needs better error handling
  3. 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.

Suggested change
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]);

Copy link

@llamapreview llamapreview bot left a 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:

  1. Consider breaking this PR into smaller, more focused changes if possible.
  2. 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

@ajhollid ajhollid merged commit 481196b into develop Jan 30, 2025
3 checks passed
@ajhollid ajhollid deleted the fix/incidents-refactor branch January 30, 2025 16:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant