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

Refactor FileBlock, FIleUpload, UserAvatar, UserHome and migrated to TanStack's query #10045

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

abhimanyurajeesh
Copy link
Contributor

@abhimanyurajeesh abhimanyurajeesh commented Jan 18, 2025

Part of #9837

@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

Release Notes

  • Refactor

    • Updated data fetching logic across multiple components using TanStack Query's useQuery hook.
    • Replaced custom query hook with native useQuery implementation.
    • Improved query key structure and data retrieval methods.
  • Performance

    • Streamlined data fetching process.
    • Enhanced query management and state handling.
  • Maintenance

    • Simplified code structure in user and file-related components.
    • Standardized approach to data querying across the application.

@abhimanyurajeesh abhimanyurajeesh requested a review from a team as a code owner January 18, 2025 13:20
Copy link
Contributor

coderabbitai bot commented Jan 18, 2025

Walkthrough

This pull request focuses on refactoring data fetching across multiple components by replacing a custom query hook with the standard useQuery hook from TanStack Query. The changes standardize data retrieval in FileBlock.tsx, FileUpload.tsx, UserAvatar.tsx, and UserHome.tsx components. The implementation introduces more explicit query key structures, utilizes a new query utility function, and leverages built-in loading and data management capabilities of the react-query library.

Changes

File Change Summary
src/components/Files/FileBlock.tsx Replaced custom useTanStackQueryInstead with useQuery, updated query key structure, modified data access method
src/components/Files/FileUpload.tsx Refactored activeFilesQuery, archivedFilesQuery, and dischargeSummaryQuery to use useQuery, updated refetchAll function
src/components/Users/UserAvatar.tsx Migrated to useQuery with new query key and function, updated loading state handling
src/components/Users/UserHome.tsx Simplified user data fetching using useQuery, streamlined error handling and loading state management

Sequence Diagram

sequenceDiagram
    participant Component
    participant useQuery
    participant query Utility
    participant API

    Component->>useQuery: Configure query
    useQuery->>query Utility: Call with params
    query Utility->>API: Make network request
    API-->>query Utility: Return data
    query Utility-->>useQuery: Process response
    useQuery-->>Component: Provide data and state
Loading

Possibly related PRs

Suggested labels

tested, reviewed

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 Queries dance with grace and might,
TanStack's magic takes its flight!
From custom hooks to streamlined code,
Our data fetching finds its road.
Refactored with a rabbit's glee,
Efficiency now runs free! 🚀


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

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 Jan 18, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 3cfb5f0
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/678f9760dcdf780008a18f2c
😎 Deploy Preview https://deploy-preview-10045--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: 1

🧹 Nitpick comments (3)
src/components/Users/UserHome.tsx (1)

39-51: Handle error state in data fetching

Currently, the component only handles the loading state and the absence of userData but does not handle errors that might occur during the data fetching process. It's important to provide feedback to the user when an error occurs to improve the user experience.

Consider adding error handling by checking for the error state returned by useQuery:

const { data: userData, isLoading, error } = useQuery({ ... });

if (isLoading) {
  return <Loading />;
}

if (error) {
  return <div>Error fetching user details</div>; // Replace with a user-friendly error component
}

This ensures that users are informed if there's an issue retrieving the user details.

src/components/Files/FileUpload.tsx (1)

137-147: Add enabled option to useQuery hooks to prevent unnecessary queries

The useQuery hooks for activeFilesQuery and archivedFilesQuery do not have the enabled option specified. If associatedId is empty or invalid, these queries may run unnecessarily, leading to redundant API calls or potential errors.

Include the enabled option to ensure the queries only execute when associatedId is valid:

useQuery({
  queryKey: ["viewUpload", "active", type, associatedId, offset],
  queryFn: query(routes.viewUpload, {
    // ...
  }),
+ enabled: Boolean(associatedId),
});

Apply the same change to the archivedFilesQuery:

useQuery({
  queryKey: ["viewUpload", "archived", type, associatedId, offset],
  queryFn: query(routes.viewUpload, {
    // ...
  }),
+ enabled: Boolean(associatedId),
});

This prevents unnecessary queries when associatedId is not available.

Also applies to: 150-163

src/components/Users/UserAvatar.tsx (1)

31-38: Handle error state in data fetching

The component currently only checks for the loading state and absence of userData, but it doesn't handle errors that might occur during the data fetching process using useQuery. Including error handling improves the robustness of the component and provides better feedback to the user.

Modify the code to handle errors by updating the destructured values and adding an error check:

const { data: userData, isLoading, error } = useQuery({ ... });

if (isLoading) {
  return <Loading />;
}

if (error) {
  return <div>Error loading user data</div>; // Replace with an appropriate error component
}

This ensures users are notified when there's an issue fetching the user data.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 206ee47 and d210a44.

📒 Files selected for processing (4)
  • src/components/Files/FileBlock.tsx (4 hunks)
  • src/components/Files/FileUpload.tsx (4 hunks)
  • src/components/Users/UserAvatar.tsx (3 hunks)
  • src/components/Users/UserHome.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (4)
src/components/Files/FileBlock.tsx (4)

1-1: LGTM! Clean transition to TanStack Query.

The import changes correctly reflect the migration from a custom query hook to TanStack Query's official implementation.

Also applies to: 16-16


38-43: Excellent query key structure!

The array-based query key structure with multiple elements (path, file.id, fileManager.type, associating_id) provides excellent cache management and invalidation capabilities. This approach aligns with TanStack Query best practices.


94-94: LGTM! Correct data access pattern.

The update to fileData?.read_signed_url correctly reflects TanStack Query's data structure, maintaining null safety with optional chaining.


37-48: Consider adding input validation for file.id.

While the query implementation is solid, the fallback to an empty string for file.id might indicate missing validation. Consider validating the file ID before making the query.

src/components/Files/FileUpload.tsx Outdated Show resolved Hide resolved
@abhimanyurajeesh
Copy link
Contributor Author

@rithviknishad requesting for review :), Thank you

src/components/Files/FileBlock.tsx Outdated Show resolved Hide resolved
src/components/Files/FileUpload.tsx Outdated Show resolved Hide resolved
src/components/Files/FileUpload.tsx Outdated Show resolved Hide resolved
src/components/Files/FileUpload.tsx Outdated Show resolved Hide resolved
src/components/Files/FileUpload.tsx Outdated Show resolved Hide resolved
src/components/Users/UserHome.tsx Outdated Show resolved Hide resolved
…ery key structure and enhance data handling with React Query
@abhimanyurajeesh
Copy link
Contributor Author

@rithviknishad I believe, I have made the required changes, kindly look into it and let me know if I made a mistake : )

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

🧹 Nitpick comments (5)
src/components/Users/UserHome.tsx (2)

41-47: Consider memoizing the query key and making the enabled condition more explicit.

The query implementation looks good, but could be improved for better performance and clarity.

-  const { data: userData, isLoading } = useQuery({
-    queryKey: ["getUserDetails", username],
-    queryFn: query(routes.getUserDetails, {
-      pathParams: { username },
-    }),
-    enabled: Boolean(username),
-  });
+  const queryKey = useMemo(() => ["getUserDetails", username], [username]);
+  const { data: userData, isLoading } = useQuery({
+    queryKey,
+    queryFn: query(routes.getUserDetails, {
+      pathParams: { username },
+    }),
+    enabled: username !== undefined && username !== null,
+  });

49-53: Consider memoizing the invalidation function.

The invalidation function should be memoized to prevent unnecessary re-renders.

-  const invalidateUserDetails = () => {
-    queryClient.invalidateQueries({
-      queryKey: ["getUserDetails", username],
-    });
-  };
+  const invalidateUserDetails = useCallback(() => {
+    queryClient.invalidateQueries({
+      queryKey: ["getUserDetails", username],
+    });
+  }, [queryClient, username]);
src/components/Files/FileBlock.tsx (1)

37-43: Consider adding stale time configuration for the file data.

The query looks good, but adding staleTime could optimize refetching behavior for file data that doesn't change frequently.

   const { data: fileData } = useQuery({
     queryKey: ["file", { id: file.id, type: fileManager.type, associating_id }],
     queryFn: query(routes.retrieveUpload, {
       queryParams: { file_type: fileManager.type, associating_id },
       pathParams: { id: file.id || "" },
     }),
-    enabled: filetype === "AUDIO" && !file.is_archived,
+    enabled: filetype === "AUDIO" && !file.is_archived,
+    staleTime: 5 * 60 * 1000, // 5 minutes
   });
src/components/Files/FileUpload.tsx (2)

123-135: Consider memoizing query invalidation keys.

The refetch function could be optimized by memoizing the query keys.

+  const activeQueryKey = useMemo(() => ["viewUpload", "active", type, associatedId], [type, associatedId]);
+  const archivedQueryKey = useMemo(() => ["viewUpload", "archived", type, associatedId], [type, associatedId]);
+  const dischargeSummaryQueryKey = useMemo(() => ["viewUpload", "discharge_summary", associatedId], [associatedId]);

-  const refetchAll = () => {
+  const refetchAll = useCallback(() => {
     queryClient.invalidateQueries({
-      queryKey: ["viewUpload", "active", type, associatedId],
+      queryKey: activeQueryKey,
     });
     queryClient.invalidateQueries({
-      queryKey: ["viewUpload", "archived", type, associatedId],
+      queryKey: archivedQueryKey,
     });
     if (type === "consultation") {
       queryClient.invalidateQueries({
-        queryKey: ["viewUpload", "discharge_summary", associatedId],
+        queryKey: dischargeSummaryQueryKey,
       });
     }
-  };
+  }, [queryClient, activeQueryKey, archivedQueryKey, dischargeSummaryQueryKey, type]);

180-185: Consider simplifying the queries object.

The queries object could be simplified using object shorthand notation.

   const queries = {
-    UNARCHIVED: { data: activeFiles, isLoading: activeFilesLoading },
-    ARCHIVED: { data: archivedFiles, isLoading: archivedFilesLoading },
-    DISCHARGE_SUMMARY: {
-      data: dischargeSummary,
-      isLoading: dischargeSummaryLoading,
-    },
+    UNARCHIVED: { data: activeFiles, isLoading: activeFilesLoading },
+    ARCHIVED: { data: archivedFiles, isLoading: archivedFilesLoading },
+    DISCHARGE_SUMMARY: { data: dischargeSummary, isLoading: dischargeSummaryLoading },
   };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d210a44 and 9bc53a5.

📒 Files selected for processing (3)
  • src/components/Files/FileBlock.tsx (4 hunks)
  • src/components/Files/FileUpload.tsx (4 hunks)
  • src/components/Users/UserHome.tsx (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (1)
src/components/Files/FileUpload.tsx (1)

176-176: ⚠️ Potential issue

Normalize case when checking type for discharge summary query.

Based on past review comments, there's still a case sensitivity issue in the enabled condition.

-      enabled: type === "consultation",
+      enabled: type.toLowerCase() === "consultation",

Likely invalid or redundant comment.

src/components/Files/FileBlock.tsx Show resolved Hide resolved
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

🧹 Nitpick comments (2)
src/components/Users/UserHome.tsx (2)

40-46: Add error handling to the query implementation.

While the query implementation is good, consider handling error states to improve user experience.

-  const { data: userData, isLoading } = useQuery({
+  const { data: userData, isLoading, error } = useQuery({
     queryKey: ["getUserDetails", username],
     queryFn: query(routes.getUserDetails, {
       pathParams: { username },
     }),
     enabled: Boolean(username),
   });

+  if (error) {
+    return <ErrorPage error={error} />;
+  }

48-50: Separate loading and data availability checks.

Consider handling loading and data availability separately for more precise error handling and better debugging.

-  if (isLoading || !userData) {
+  if (isLoading) {
     return <Loading />;
   }
+  
+  if (!userData) {
+    return <ErrorPage error="No user data available" />;
+  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9bc53a5 and 3cfb5f0.

📒 Files selected for processing (1)
  • src/components/Users/UserHome.tsx (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (2)
src/components/Users/UserHome.tsx (2)

1-1: LGTM! Clean import changes for TanStack Query integration.

The imports are correctly updated to support the migration to TanStack Query's useQuery hook.

Also applies to: 16-16


131-131: LGTM! Properly implemented feedback from previous review.

The component correctly implements the previous review feedback by removing the refetch prop drilling, aligning with the recommendation to use invalidateQueries directly where needed.

Comment on lines -145 to +131
<SelectedTab
userData={userData}
username={username}
{...props}
refetchUserData={refetchUserDetails}
/>
<SelectedTab userData={userData} username={username} {...props} />
Copy link
Member

Choose a reason for hiding this comment

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

you should be deleting the prop too from here and update all tabs to not call that anymore and instead use invalidate queries.

image

Copy link
Contributor Author

Choose a reason for hiding this comment

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

which is this file, is this userColumns?

Copy link
Member

Choose a reason for hiding this comment

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

yup

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.

2 participants