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 1 commit 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 d210a44
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/678baa8d09a51e000806e529
😎 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.

Comment on lines +164 to +178
const { data: dischargeSummaryQuery, isLoading: dischargeSummaryLoading } =
useQuery({
queryKey: ["viewUpload", "discharge_summary", associatedId, offset],
queryFn: query(routes.viewUpload, {
queryParams: {
file_type: "discharge_summary",
associating_id: associatedId,
is_archived: false,
limit: RESULTS_PER_PAGE_LIMIT,
offset: offset,
silent: true,
},
}),
enabled: type === "consultation",
});
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 18, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure consistent casing of type when checking conditions

In the useQuery for dischargeSummaryQuery, the enabled condition is checking type === "consultation". However, elsewhere in the code, type appears to be in uppercase (e.g., "CONSULTATION" in the associatedId mapping). This inconsistency could prevent the query from running as expected.

To ensure the condition works properly, normalize the type to be uppercase or lowercase consistently throughout the code. For example:

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

Alternatively, if type should be lowercase, adjust the rest of the code to match.

📝 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
const { data: dischargeSummaryQuery, isLoading: dischargeSummaryLoading } =
useQuery({
queryKey: ["viewUpload", "discharge_summary", associatedId, offset],
queryFn: query(routes.viewUpload, {
queryParams: {
file_type: "discharge_summary",
associating_id: associatedId,
is_archived: false,
limit: RESULTS_PER_PAGE_LIMIT,
offset: offset,
silent: true,
},
}),
enabled: type === "consultation",
});
const { data: dischargeSummaryQuery, isLoading: dischargeSummaryLoading } =
useQuery({
queryKey: ["viewUpload", "discharge_summary", associatedId, offset],
queryFn: query(routes.viewUpload, {
queryParams: {
file_type: "discharge_summary",
associating_id: associatedId,
is_archived: false,
limit: RESULTS_PER_PAGE_LIMIT,
offset: offset,
silent: true,
},
}),
enabled: type.toUpperCase() === "CONSULTATION",
});

Copy link
Member

Choose a reason for hiding this comment

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

@abhimanyurajeesh confirm this and mark this as resolved or make changes if needed.

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@abhimanyurajeesh
Copy link
Contributor Author

@rithviknishad requesting for review :), Thank you

Comment on lines +38 to +43
queryKey: [
routes.retrieveUpload.path,
file.id,
fileManager.type,
associating_id,
],
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
queryKey: [
routes.retrieveUpload.path,
file.id,
fileManager.type,
associating_id,
],
queryKey: [
"file",
{ id: file.id, type: fileManager.type, associating_id },
],

limit: RESULTS_PER_PAGE_LIMIT,
offset: offset,
},
const { data: activeFilesQuery, isLoading: activeFilesLoading } = useQuery({
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
const { data: activeFilesQuery, isLoading: activeFilesLoading } = useQuery({
const { data: activeFiles, isLoading: activeFilesLoading } = useQuery({

prefetch: type === "consultation",
silent: true,
});
const { data: archivedFilesQuery, isLoading: archivedFilesLoading } =
Copy link
Member

Choose a reason for hiding this comment

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

these aren't queries, these are data objects right?

Suggested change
const { data: archivedFilesQuery, isLoading: archivedFilesLoading } =
const { data: archivedFiles, isLoading: archivedFilesLoading } =

}),
});

const { data: dischargeSummaryQuery, isLoading: dischargeSummaryLoading } =
Copy link
Member

Choose a reason for hiding this comment

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

here too

Comment on lines +164 to +178
const { data: dischargeSummaryQuery, isLoading: dischargeSummaryLoading } =
useQuery({
queryKey: ["viewUpload", "discharge_summary", associatedId, offset],
queryFn: query(routes.viewUpload, {
queryParams: {
file_type: "discharge_summary",
associating_id: associatedId,
is_archived: false,
limit: RESULTS_PER_PAGE_LIMIT,
offset: offset,
silent: true,
},
}),
enabled: type === "consultation",
});
Copy link
Member

Choose a reason for hiding this comment

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

@abhimanyurajeesh confirm this and mark this as resolved or make changes if needed.

const {
data: userData,
isLoading,
refetch: refetchUserDetails,
Copy link
Member

Choose a reason for hiding this comment

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

let's use invalidateQueries instead of taking refetch

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