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: Display Care Loading Icon Instead of "No Assets Found" on Asset Tab Revisit on advanced filter #9205

Conversation

Mahendar0701
Copy link
Contributor

@Mahendar0701 Mahendar0701 commented Nov 25, 2024

Proposed Changes

image

  • Added margin for sample test history

image

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Enhanced state management for asset data in the AssetsList component.
    • Improved loading and rendering logic to provide clearer user feedback during asset loading.
  • Bug Fixes

    • Streamlined asset existence checks, ensuring accurate display of asset information or "No Assets Found" messages.

@Mahendar0701 Mahendar0701 requested a review from a team as a code owner November 25, 2024 16:04
Copy link
Contributor

coderabbitai bot commented Nov 25, 2024

Walkthrough

The changes in this pull request enhance the AssetsList component by improving state management and rendering logic related to asset data. A new state variable is introduced to fetch asset information, and the loading condition is refined to ensure accurate display of loading states and asset availability. The logic for determining asset existence is simplified, and the CountBlock component's loading prop is updated to align with the new data state.

Changes

File Path Change Summary
src/components/Assets/AssetsList.tsx - Introduced data state variable from useQuery for asset fetching.
- Updated loading condition to check both loading and data.
- Simplified asset existence check using data.count.
- Updated CountBlock loading prop to reflect the new data state.

Assessment against linked issues

Objective Addressed Explanation
Loading icon should appear until filtered results are loaded. (#9202)
"No assets found" message should only display if no results exist. (#9202)

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • Jacobjeevan
  • rithviknishad
  • shivankacker

🐰 In the land of assets, we hop and play,
With loading icons brightening the way.
No more "found none," just data in sight,
Our component now shines, oh what a delight!
So let’s fetch and display, with joy we declare,
A world full of assets, beyond compare! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c07cb3a and 7f15aea.

📒 Files selected for processing (1)
  • src/components/Assets/AssetsList.tsx (3 hunks)
🔇 Additional comments (3)
src/components/Assets/AssetsList.tsx (3)

72-76: LGTM: Clean destructuring of useQuery hook

The addition of data to the destructured values from useQuery is clean and follows best practices.


377-377: LGTM: Consistent loading state in CountBlock

The loading prop update maintains consistency with the main component's loading state management.


216-222: LGTM: Improved loading state management

The updated condition loading || !data correctly handles the initial loading state and subsequent data fetching, preventing premature "No assets found" messages.

Let's verify that this loading state pattern is consistent across similar components:

✅ Verification successful

The previous ast-grep pattern might have failed due to syntax. Let's try using ripgrep to find loading state patterns in TypeScript/TSX files, focusing on conditional blocks that include loading checks and the Loading component.


Let's try without file type restrictions since the tsx extension might not be recognized in the sandbox environment.


Loading state pattern is consistent with codebase practices

The updated condition loading || !data in AssetsList.tsx aligns well with the loading state patterns used throughout the codebase. We found similar patterns in other components:

  • ResourceDetails.tsx: if (loading || !data)
  • CriticalCareEditor.tsx: if (query.loading || !query.data)
  • AuthUserProvider.tsx: if (loading || !res)

The implementation follows the established pattern for handling loading states and undefined data in the application, ensuring consistent user experience across components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar loading state patterns in other list components
ast-grep --pattern 'if ($loading || !$data) {
  $$$
}'

Length of output: 56


Script:

#!/bin/bash
# Search for loading state patterns in list components using ripgrep
rg -U "if.*loading.*\{[\s\S]*?Loading" --type ts --type tsx -A 5

Length of output: 94


Script:

#!/bin/bash
# Search for loading state patterns in all files
rg -U "if.*loading.*\{[\s\S]*?Loading" -A 5

Length of output: 10331


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

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

netlify bot commented Nov 25, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 7f15aea
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6746df8ea39e8c000844d293
😎 Deploy Preview https://deploy-preview-9205--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@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: 0

🧹 Outside diff range and nitpick comments (4)
src/components/Patient/SampleDetails.tsx (1)

267-270: LGTM! Consider extracting the className to a constant.

The addition of the key prop is a good practice for React list rendering. The visual styling improvements with margin and border enhance consistency.

Consider extracting the className string to a constant or CSS module for better maintainability and reusability:

+const FLOW_CARD_CLASS_NAME = "mb-2 shadow-sm border border-secondary-300";

 const renderFlow = (flow: FlowModel) => {
   return (
     <Card
       key={flow.id}
-      className="mb-2 shadow-sm border border-secondary-300"
+      className={FLOW_CARD_CLASS_NAME}
     >
src/components/Assets/AssetsList.tsx (3)

Line range hint 213-221: Revise the conditional logic to correctly handle loading and empty states

The current condition loading || !assetsExist will show the loading indicator both during loading and when there are no assets. This doesn't align with the PR objective of only showing the loading state during data fetch.

Apply this diff to fix the logic:

-  if (loading || !assetsExist) {
+  if (loading) {
    manageAssets = (
      <div className="col-span-3 w-full py-8 text-center">
        <Loading />
      </div>
    );
-  } else if (assetsExist) {
+  } else if (!assetsExist) {
+    manageAssets = (
+      <div className="col-span-3 w-full rounded-lg bg-white p-2 py-8 pt-4 text-center">
+        <p className="text-2xl font-bold text-secondary-600">No Assets Found</p>
+      </div>
+    );
+  } else {

This change will:

  1. Show loading indicator only during the loading state
  2. Show "No Assets Found" when there are genuinely no assets
  3. Show the asset list when assets exist

Line range hint 1-600: Consider the following improvements for better maintainability and user experience

  1. Consolidate loading states:
  • Currently using both isLoading and loading states which could lead to inconsistent UX
  • Consider using a single loading state manager or use more specific names like isQRScanningLoading
  1. Enhance error handling for QR scanning:
  • Add specific error messages for different failure scenarios
  • Consider adding retry mechanism for failed scans
  1. Performance optimizations:
  • Consider memoizing the asset list rendering
  • Use useCallback for handlers like accessAssetIdFromQR

Example implementation for memoization:

import { useMemo, useCallback } from 'react';

// Memoize the asset list
const renderAssetList = useMemo(() => (
  <div className="grid grid-cols-1 gap-2 md:-mx-8 md:grid-cols-2 lg:grid-cols-3">
    {assets.map((asset: AssetData) => (
      // ... existing render logic
    ))}
  </div>
), [assets]);

// Memoize the QR handler
const handleQRScan = useCallback(async (assetURL: string) => {
  // ... existing QR handling logic
}, []);

Line range hint 89-142: Enhance error handling in QR code scanning

The current error handling uses generic messages and doesn't distinguish between different error types. Consider implementing more specific error handling for better user feedback.

 const accessAssetIdFromQR = async (assetURL: string) => {
   try {
     setIsLoading(true);
     setIsScannerActive(false);
     if (!isValidURL(assetURL)) {
       setIsLoading(false);
       Notification.Error({
-        msg: t("invalid_asset_id_msg"),
+        msg: t("invalid_qr_url_format"),
       });
       return;
     }
     const params = parseQueryParams(assetURL);
     const assetId = params.asset || params.assetQR;
 
     if (assetId) {
       const { data } = await request(routes.listAssetQR, {
         pathParams: { qr_code_id: assetId },
       });
       if (!data) {
         setIsLoading(false);
         Notification.Error({
-          msg: t("invalid_asset_id_msg"),
+          msg: t("qr_code_not_found"),
         });
         return;
       }
       const { data: assetData } = await request(routes.listAssets, {
         query: { qr_code_id: assetId, limit: 1 },
       });
       if (assetData?.results.length === 1) {
         navigate(
           `/facility/${assetData.results[0].location_object.facility?.id}/assets/${assetData.results[0].id}`,
         );
       } else {
         setIsLoading(false);
         Notification.Error({
-          msg: t("asset_not_found_msg"),
+          msg: t("asset_not_linked_to_qr"),
         });
       }
     } else {
       setIsLoading(false);
       Notification.Error({
-        msg: t("invalid_asset_id_msg"),
+        msg: t("missing_asset_id_in_qr"),
       });
     }
   } catch (err) {
+    console.error('QR Scan Error:', err);
     Notification.Error({
-      msg: t("invalid_asset_id_msg"),
+      msg: t("qr_scan_error"),
     });
   } finally {
     setIsLoading(false);
   }
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fdfc53d and fae3d3d.

📒 Files selected for processing (2)
  • src/components/Assets/AssetsList.tsx (1 hunks)
  • src/components/Patient/SampleDetails.tsx (1 hunks)

src/components/Assets/AssetsList.tsx Outdated Show resolved Hide resolved
@Mahendar0701
Copy link
Contributor Author

Hey @Jacobjeevan i have done the required changes . Once look into it

Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

This issue doesn't seem to be happening for tabs other than Assets tab. Most of the other tabs are having the similar implementation. I'd recommend actually debugging why that "no assets found" is coming in the first place as how it's mentioned in the issue.

Using timer to solve this is more of a hack that hides the root cause of the issue and is not the right solution.

Ideally the loading state provided by the useQuery should be enough to show the Loading state and if not loading, data.results.length being 0 would convey if it's actually empty assets for the applied filters.

@rithviknishad rithviknishad added invalid This doesn't seem right and removed needs testing needs review labels Nov 26, 2024
@Mahendar0701
Copy link
Contributor Author

This issue doesn't seem to be happening for tabs other than Assets tab. Most of the other tabs are having the similar implementation. I'd recommend actually debugging why that "no assets found" is coming in the first place as how it's mentioned in the issue.

Yes, The issue is not occurring in other tabs; it is only happening on the Assets page. I have checked the code for the other tabs, and they have a similar implementation. However, in AssetsList.tsx, we are not using destructuring to assign data in useQuery. In contrast, in the other pages, data is being destructured, and the loading logic is also implemented using data?.count.

So, I have updated the AssetsList.tsx loading logic to match the implementation of the other tabs.

Using timer to solve this is more of a hack that hides the root cause of the issue and is not the right solution.

I have removed it

Ideally the loading state provided by the useQuery should be enough to show the Loading state and if not loading, data.results.length being 0 would convey if it's actually empty assets for the applied filters.

On page revisit, the data is initially undefined, which is why the issue is occurring. This condition was not properly handled
along with the loading state in the if statement in AssetsList.tsx, like it was done in other tabs.

@github-actions github-actions bot added needs-triage question Further information is requested labels Nov 27, 2024
Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

LGTM; just a minor correction

src/components/Patient/SampleDetails.tsx Outdated Show resolved Hide resolved
src/components/Assets/AssetsList.tsx Outdated Show resolved Hide resolved
@rithviknishad rithviknishad removed invalid This doesn't seem right question Further information is requested needs-triage labels Nov 27, 2024
@rithviknishad
Copy link
Member

@Jacobjeevan review required

@rithviknishad
Copy link
Member

Closing as root issue was fixed in #9222

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