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

[Netmanager-app]improved on the grids hooks #2544

Open
wants to merge 6 commits into
base: staging
Choose a base branch
from
Open

Conversation

danielmarv
Copy link
Member

@danielmarv danielmarv commented Mar 4, 2025

Summary of Changes (What does this PR do?)

  • The analytics page had some issues which were caused by grids hook

Status of maturity (all need to be checked before merging):

  • I've tested this locally
  • I consider this code done
  • This change ready to hit production in its current state
  • The title of the PR states what changed and the related issues number (used for the release note).
  • I've included issue number in the "Closes #ISSUE-NUMBER" part of the "What are the relevant tickets?" section to link the issue.
  • I've updated corresponding documentation for the changes in this PR.
  • I have written unit and/or e2e tests for my change(s).

How should this be manually tested?

  • Please include the steps to be done inorder to setup and test this PR.

What are the relevant tickets?

Screenshots (optional)

Summary by CodeRabbit

  • New Features

    • Introduced a loading skeleton for the analytics dashboard that displays structured visual placeholders (header, charts, table, and metrics) during data fetching.
    • Enhanced the dashboard with a spinner indicator to deliver a smoother loading experience.
  • Chores

    • Upgraded the animation library dependency to improve performance and ensure smoother transitions.

Copy link

coderabbitai bot commented Mar 4, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a new React component, AnalyticsSkeleton, that provides a skeleton UI for the analytics dashboard. It also includes several code formatting refinements and minor logic adjustments in the analytics index component, cleans up commented-out code in the organization module, and updates the useGrids hook by removing a parameter and simplifying error handling. Additionally, the version of the framer-motion dependency has been updated. The overall changes focus on visual loading improvements, clearer state representation, and code style consistency.

Changes

Files Summary
src/netmanager-app/components/Analytics/…/analytics-skeleton.tsx Added a new functional component AnalyticsSkeleton to render skeleton loading elements using Card, CardContent, and Skeleton components.
src/netmanager-app/components/Analytics/index.tsx Applied code formatting adjustments, removed extraneous semicolons, added a Loader2 import, and refined loading state logic by aggregating multiple hooks’ states.
src/netmanager-app/components/Organization/create-group.tsx Removed an unused commented-out line in the onInviteMembers function.
src/netmanager-app/core/hooks/…/useGrids.ts Modified the hook signature by removing the networkId parameter, adjusted type handling by generalizing types, and added isLoading and error to the hook’s return object.
src/netmanager-app/core/hooks/useGroups.ts Removed semicolons for consistent code formatting; functional logic remains unchanged.
src/netmanager-app/package.json Updated the framer-motion dependency version from ^12.4.3 to ^12.4.7.

Sequence Diagram(s)

sequenceDiagram
    participant User as User
    participant AnalyticsPage as Analytics Index
    participant Loader as AnalyticsSkeleton
    participant Data as Data Fetcher

    User->>AnalyticsPage: Request analytics dashboard
    AnalyticsPage->>Data: Trigger data fetch
    Data-->>AnalyticsPage: Data Loading (pending)
    AnalyticsPage->>Loader: Render skeleton UI for loading state
    Data-->>AnalyticsPage: Data available
    AnalyticsPage->>User: Render complete analytics dashboard
Loading

Possibly related PRs

Suggested reviewers

  • Baalmart
  • Codebmk

Poem

In lines of code the skeleton wakes,
A placeholder dance as data partakes.
Cards and charts in waiting state,
Formatted clean, the dashboard’s fate.
A quiet tweak in every line,
Code and art in seamless design.
Cheers to progress—bright and fine!

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • JIRA integration encountered authorization issues. Please disconnect and reconnect the integration in the CodeRabbit UI.
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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.
  • @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 or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

🧹 Nitpick comments (5)
src/netmanager-app/components/Analytics/analytics-skeleton.tsx (1)

44-44: Minor cleanup: Remove trailing empty line.

There's an empty line at the end of the file that could be removed for consistency.

}
-
44
src/netmanager-app/core/hooks/useGrids.ts (1)

23-33: Type safety reduced in query callbacks.

The onSuccess and onError callbacks now use less specific types (any and Error instead of specific types like AxiosError<ErrorResponse>). While this works functionally, it reduces type safety which could lead to runtime errors if the response structure changes.

-    onSuccess: (data: any) => {
+    onSuccess: (data: { grids: Grid[] }) => {
      dispatch(setGrids(data.grids));
    },
-    onError: (error: Error) => {
+    onError: (error: AxiosError<ErrorResponse>) => {
-      dispatch(setError(error.message));
+      dispatch(setError(error.response?.data?.message || error.message));
    },
src/netmanager-app/components/Analytics/index.tsx (3)

19-19: Commented import should be enabled or removed.

The AnalyticsSkeleton component is imported but commented out. Either use it to replace the simple loading spinner or remove the import if it's not needed.

-// import { AnalyticsSkeleton } from "./analytics-skeleton"
+import { AnalyticsSkeleton } from "./analytics-skeleton"

Then replace the simple loading spinner with the skeleton UI:

-  if (isLoading) {
-    return (
-      <div className="flex items-center justify-center min-h-screen">
-        <Loader2 className="w-8 h-8 animate-spin" />
-      </div>
-    );
-  }
+  if (isLoading) {
+    return <AnalyticsSkeleton />
+  }

70-71: Use optional chaining for improved safety.

The static analysis tool correctly identified that line 70 would benefit from using optional chaining instead of the current approach.

-        : (cohorts && cohorts[0]) || null,
+        : cohorts?.[0] || null,
🧰 Tools
🪛 Biome (1.9.4)

[error] 70-70: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


74-90: Remove or uncomment the transformation code.

This commented-out code block for data transformation should either be:

  1. Implemented if it's still needed
  2. Removed if it's obsolete
  3. Documented with a comment explaining why it's preserved

Consider removing it if it's no longer needed:

-  // useEffect(()=>{
-  //   if(mapReadings) {
-  //     const values = transformDataToGeoJson(
-  //       mapReadings,
-  //       {
-  //         longitude: 'Longitude',
-  //         latitude: 'Latitude'
-  //       },
-  //       (feature) => [
-  //         feature.siteDetails && feature.siteDetails.approximate_longitude,
-  //         feature.siteDetails && feature.siteDetails.approximate_latitude
-  //       ]
-  //     );
-
-  //     setTransformedReadings(values);
-  //   }
-  // }, [mapReadings]);

Or if you're keeping it for reference, add a clear explanation:

+  // NOTE: This transformation is temporarily disabled until we implement the new map component
   // useEffect(()=>{
   //   if(mapReadings) {
   //     ...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 280275e and 97a29e5.

⛔ Files ignored due to path filters (1)
  • src/netmanager-app/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • src/netmanager-app/components/Analytics/analytics-skeleton.tsx (1 hunks)
  • src/netmanager-app/components/Analytics/index.tsx (4 hunks)
  • src/netmanager-app/components/Organization/create-group.tsx (1 hunks)
  • src/netmanager-app/core/hooks/useGrids.ts (2 hunks)
  • src/netmanager-app/core/hooks/useGroups.ts (1 hunks)
  • src/netmanager-app/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • src/netmanager-app/package.json
  • src/netmanager-app/components/Organization/create-group.tsx
  • src/netmanager-app/core/hooks/useGroups.ts
🧰 Additional context used
🪛 Biome (1.9.4)
src/netmanager-app/components/Analytics/index.tsx

[error] 70-70: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (6)
src/netmanager-app/components/Analytics/analytics-skeleton.tsx (1)

1-42: Well-structured skeleton component implementation.

This new AnalyticsSkeleton component provides an excellent visual placeholder during data loading states. The grid-based layout effectively mirrors the actual dashboard structure, creating a smooth transition between loading and loaded states. The responsive design considerations (using sm/lg breakpoints) will ensure consistent user experience across device sizes.

src/netmanager-app/core/hooks/useGrids.ts (2)

10-10: LGTM: Import statement updated appropriately.

The import statement has been simplified to include only the necessary Redux actions.


35-39: Improved return object with loading and error states.

The hook now properly returns isLoading and error states, which improves the API and makes it consistent with other hooks. This is a good improvement that gives consumers more information about the request status.

src/netmanager-app/components/Analytics/index.tsx (3)

8-8: LGTM: Added Loader2 import for loading states.

Adding the Loader2 component from lucide-react improves visual feedback during loading states.


36-41: Good consolidation of loading states.

Well done on consolidating the loading states from multiple hooks. This creates a single source of truth for the component's loading state.


161-165: Great improvement to loading UI in Download button.

The addition of a loading spinner and text change during download operations provides excellent visual feedback to users. This follows best practices for interactive UI elements.

@@ -16,24 +16,21 @@ interface ErrorResponse {
}

// Hook to get the grid summary
export const useGrids = (networkId: string) => {
export const useGrids = () => {
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Hook signature simplified - verify impact on consumers.

The function signature has been changed to remove the networkId parameter. This simplifies usage but may affect any components that were passing a non-active network ID.


🏁 Script executed:

#!/bin/bash
# Check for any instances where useGrids is called with parameters
rg "useGrids\(\S" --type tsx --type ts

Length of output: 68


Below is a revised verification step to further check for any consumers that might still be passing parameters to the updated hook signature:

Next Steps:

  • Please run the script above so we can confirm if any components are still calling useGrids with an argument.
  • If the output shows any instances, those usages will need to be updated to remove the obsolete networkId parameter.
  • If nothing is returned, it’s still a good idea to do a manual scan—especially in TSX files—to ensure there are no unintended regressions.

This additional verification is important because the earlier command failed due to the unrecognized file type "tsx". Once you’ve checked that no consumers pass parameters, the hook signature change should be safe.

Thanks for double-checking!


🏁 Script executed:

#!/bin/bash
# Check for any instances where useGrids is called with non-empty arguments
# (i.e. where there's something between the parentheses other than just whitespace).
rg "useGrids\\(\\s*[^)]" -g "*.ts" -g "*.tsx"

Length of output: 285


Action Required: Update Consumer Usage of useGrids

It appears that although the hook signature was simplified (removing the networkId parameter), there is still a consumer in the codebase invoking it with an argument:

  • File: src/netmanager-app/components/export-data/ExportForm.tsx
    Usage: const { grids } = useGrids(activeNetwork?.net_name || "");

Please remove the argument from this call to align with the updated hook signature. Verify that this change doesn't affect the component's logic or any dependent behavior.

Comment on lines +137 to +143
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<Loader2 className="w-8 h-8 animate-spin" />
</div>
);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using the AnalyticsSkeleton component.

You've created a nice AnalyticsSkeleton component but are using a simple spinner here. For better user experience, consider using the skeleton UI which would provide a closer representation of the content being loaded.

-  if (isLoading) {
-    return (
-      <div className="flex items-center justify-center min-h-screen">
-        <Loader2 className="w-8 h-8 animate-spin" />
-      </div>
-    );
-  }
+  if (isLoading) {
+    return <AnalyticsSkeleton />
+  }
📝 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
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<Loader2 className="w-8 h-8 animate-spin" />
</div>
);
}
if (isLoading) {
return <AnalyticsSkeleton />
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant