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

Removed unused feature flag handling and migrated to TanStack's query #9892

Merged
merged 7 commits into from
Jan 15, 2025

Conversation

abhimanyurajeesh
Copy link
Contributor

@abhimanyurajeesh abhimanyurajeesh commented Jan 10, 2025

Proposed Changes

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

Summary by CodeRabbit

  • New Features

    • Upgraded data fetching mechanism using React Query across multiple components.
    • Improved query handling and state management for plug configurations.
  • Bug Fixes

    • Removed deprecated feature flag management, ensuring a cleaner codebase.
  • Refactor

    • Simplified query logic in the PlugConfigEdit and PlugConfigList components.
    • Updated query and mutation hooks for better readability and performance.
    • Removed unnecessary context from the application structure.
  • Chores

    • Updated import statements and library usage.
    • Aligned code with React Query best practices.

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

coderabbitai bot commented Jan 10, 2025

Walkthrough

This pull request involves the removal of the featureFlags.tsx file and significant updates to several components, particularly PlugConfigEdit.tsx and PlugConfigList.tsx, to utilize the @tanstack/react-query library for data fetching and mutation. The modifications streamline the query handling by replacing previous implementations with structured configurations using useQuery and useMutation. Additionally, the deletePlugConfig API route has been clarified to indicate that it does not require a request body. Overall, the changes enhance the code structure and remove the feature flagging mechanism from the application.

Changes

File Change Summary
src/Utils/featureFlags.tsx Removed the entire file, including FeatureFlagsProvider, useFeatureFlags, and related types/interfaces.
src/pages/Apps/PlugConfigEdit.tsx Updated imports to use useMutation and useQuery from @tanstack/react-query, simplified request handling for create/update/delete operations.
src/pages/Apps/PlugConfigList.tsx Migrated to structured useQuery configuration with queryKey and queryFn, renamed loading to isLoading.
src/Utils/request/api.tsx Added TBody property to deletePlugConfig, indicating no request body is needed for DELETE requests.
src/App.tsx Removed FeatureFlagsProvider from the component tree within AuthUserProvider.
src/components/Facility/models.tsx Removed import of FeatureFlag and deleted facility_flags property from FacilityModel.
src/components/Users/models.tsx Removed user_flags property from UserModel.

Possibly related PRs

  • Patient Registration form refactor #9854: This PR is related as it involves the PatientRegistration component, which may utilize the feature flags context for conditional rendering or validation, especially since it deals with patient data management.

Suggested labels

tested, reviewed

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 In the meadow where code does play,
Feature flags have hopped away!
Queries now dance with a structured tune,
Fetching data, morning to noon.
A rabbit's joy in the clean display! 🌼


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 902fefd and f1c409d.

📒 Files selected for processing (1)
  • src/pages/Apps/PlugConfigEdit.tsx (4 hunks)
🔇 Additional comments (5)
src/pages/Apps/PlugConfigEdit.tsx (5)

1-2: LGTM! Clean migration to TanStack Query.

The import statements are well-organized, and the migration from the previous query implementation to TanStack Query is clean and correct.

Also applies to: 25-26


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

While the query implementation is correct, it lacks error handling which was suggested in a previous review.

Add error handling to improve user experience:

  const { data: existingConfig, isLoading } = useQuery({
    queryKey: ["plug-config", slug],
    queryFn: query(routes.plugConfig.getPlugConfig, { pathParams: { slug } }),
    enabled: !isNew,
+   onError: (error) => {
+     console.error("Error fetching existing config:", error);
+     // Use your app's toast/notification system
+     toast.error("Failed to load configuration");
+   },
  });

56-61: Add error handling to the upsert mutation.

The mutation implementation lacks error handling which could lead to silent failures.

Add error handling:

  const { mutate: upsertConfig } = useMutation({
    mutationFn: isNew
      ? mutate(routes.plugConfig.createPlugConfig)
      : mutate(routes.plugConfig.updatePlugConfig, { pathParams: { slug } }),
    onSuccess: () => navigate("/apps"),
+   onError: (error) => {
+     console.error("Error saving config:", error);
+     // Use your app's toast/notification system
+     toast.error("Failed to save configuration");
+   },
  });

63-68: Add error handling to the delete mutation.

The delete mutation should handle errors to provide feedback to users.

Add error handling:

  const { mutate: deleteConfig } = useMutation({
    mutationFn: mutate(routes.plugConfig.deletePlugConfig, {
      pathParams: { slug },
    }),
    onSuccess: () => navigate("/apps"),
+   onError: (error) => {
+     console.error("Error deleting config:", error);
+     // Use your app's toast/notification system
+     toast.error("Failed to delete configuration");
+   },
  });

136-138: Add JSON validation for the meta field.

The meta field accepts any input without validation, which could lead to errors during submission.

Consider adding validation:

  <Textarea
    value={config.meta}
    onChange={(e) => {
+     const newValue = e.target.value;
+     try {
+       // Validate JSON as user types
+       JSON.parse(newValue);
+       setConfig((prev) => ({ ...prev, meta: newValue }));
+     } catch (error) {
+       // Still update the field but show error state
+       setConfig((prev) => ({ ...prev, meta: newValue }));
+       // Use your app's form validation system
+       setError("meta", "Invalid JSON format");
+     }
    }}
    rows={10}
+   // Add error styles if validation fails
+   className={errors.meta ? "border-red-500" : ""}
  />

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 10, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit f1c409d
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67861b9178f33200089e43e0
😎 Deploy Preview https://deploy-preview-9892--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: 6

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 35c89cb and cb3341f.

📒 Files selected for processing (3)
  • src/Utils/featureFlags.tsx (2 hunks)
  • src/pages/Apps/PlugConfigEdit.tsx (4 hunks)
  • src/pages/Apps/PlugConfigList.tsx (2 hunks)
🔇 Additional comments (12)
src/pages/Apps/PlugConfigEdit.tsx (6)

1-2: Imports updated to use '@tanstack/react-query' and 'raviger'

The imports of useMutation and useQuery from @tanstack/react-query and useNavigate from raviger are appropriate.


25-26: Importing 'mutate' and 'query' utilities

The mutate and query functions are correctly imported from "@/Utils/request/mutate" and "@/Utils/request/query" for data fetching and mutation.


33-35: Initialization of 'navigate' and 'isNew' variables

The navigate function is correctly initialized using useNavigate(), and isNew is appropriately set based on the slug.


76-76: Submit handler updated to use 'createOrUpdateConfig.mutate'

The handleSubmit function correctly calls createOrUpdateConfig.mutate with the configuration payload.


79-80: Updated 'handleDelete' to use mutation

The handleDelete function correctly calls deleteConfig.mutate() to trigger the deletion.


83-83: Updated loading state check to use 'isLoading'

The loading state is correctly updated to use isLoading from useQuery.

src/pages/Apps/PlugConfigList.tsx (3)

1-1: Import 'useQuery' from '@tanstack/react-query'

The import statement correctly imports useQuery from @tanstack/react-query.


19-19: Import 'query' utility

The query function is imported from "@/Utils/request/query" to be used with useQuery.


28-28: Updated loading state check to use 'isLoading'

The loading state check is correctly updated to use isLoading from useQuery.

src/Utils/featureFlags.tsx (3)

1-1: Import 'useQuery' from '@tanstack/react-query'

The import statement correctly imports useQuery from @tanstack/react-query.


9-9: Import 'query' utility

The query function is imported from "@/Utils/request/query" for use in data fetching.


60-61: Determine 'facilityId' based on 'facility' parameter

The facilityId is correctly derived from the facility parameter, handling both string IDs and facility objects.

src/pages/Apps/PlugConfigEdit.tsx Outdated Show resolved Hide resolved
src/pages/Apps/PlugConfigEdit.tsx Outdated Show resolved Hide resolved
src/pages/Apps/PlugConfigEdit.tsx Outdated Show resolved Hide resolved
src/pages/Apps/PlugConfigEdit.tsx Show resolved Hide resolved
src/pages/Apps/PlugConfigList.tsx Outdated Show resolved Hide resolved
src/Utils/featureFlags.tsx Outdated Show resolved Hide resolved
src/Utils/featureFlags.tsx Outdated Show resolved Hide resolved
src/pages/Apps/PlugConfigEdit.tsx Outdated Show resolved Hide resolved
src/pages/Apps/PlugConfigEdit.tsx Outdated Show resolved Hide resolved
src/pages/Apps/PlugConfigEdit.tsx Outdated Show resolved Hide resolved
src/pages/Apps/PlugConfigEdit.tsx Outdated Show resolved Hide resolved
src/pages/Apps/PlugConfigEdit.tsx Outdated Show resolved Hide resolved
src/pages/Apps/PlugConfigList.tsx Outdated Show resolved Hide resolved
@abhimanyurajeesh
Copy link
Contributor Author

@coderabbitai check if the requested changes were made.

Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Tip

For best results, initiate chat on the files or code changes.

@abhimanyurajeesh I don't see any previous review comments or requested changes in the PR history. Could you please specify which changes you would like me to verify? This will help me provide a more accurate assessment.

 (\__/)
(•ㅅ•)  
/   づ  Curious about which changes to check!
🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Fetch PR comments to understand what changes were requested
gh pr view 9892 --json comments --jq '.comments[].body'

Length of output: 14687

@abhimanyurajeesh
Copy link
Contributor Author

Tip

For best results, initiate chat on the files or code changes.

@abhimanyurajeesh I don't see any previous review comments or requested changes in the PR history. Could you please specify which changes you would like me to verify? This will help me provide a more accurate assessment.

 (\__/)
(•ㅅ•)  
/   づ  Curious about which changes to check!

🔗 Analysis chain
🏁 Scripts executed

https://github.com/ohcnetwork/care_fe/pull/9892/files/cb3341f4702eb443c529856db193e3ebc8baf65f
here

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 (1)
src/pages/Apps/PlugConfigList.tsx (1)

23-26: Consider adding error handling to useQuery.

The query configuration looks good, but it would benefit from error handling to improve user experience.

  const { data, isLoading } = useQuery({
    queryKey: ["list-configs"],
    queryFn: query(routes.plugConfig.listPlugConfigs),
+   onError: (error) => {
+     console.error("Error fetching plug configs:", error);
+     // Consider using your app's toast/notification system
+   },
  });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cb3341f and 689ecdb.

📒 Files selected for processing (4)
  • src/Utils/featureFlags.tsx (2 hunks)
  • src/Utils/request/api.tsx (1 hunks)
  • src/pages/Apps/PlugConfigEdit.tsx (4 hunks)
  • src/pages/Apps/PlugConfigList.tsx (2 hunks)
🔇 Additional comments (7)
src/Utils/request/api.tsx (1)

420-420: LGTM! Good practice to explicitly define void body type.

The addition of TBody: Type<void>() clearly indicates that the DELETE endpoint doesn't expect a request body, improving type safety and code clarity.

src/pages/Apps/PlugConfigList.tsx (1)

28-28: LGTM! Good use of loading state.

The loading state is properly handled using the standard isLoading flag from React Query.

src/Utils/featureFlags.tsx (1)

60-67: LGTM! Well-structured query configuration with good practices.

The implementation shows several good practices:

  • Proper query key structure with facility ID
  • Type-safe path params
  • Conditional query execution using enabled
src/pages/Apps/PlugConfigEdit.tsx (4)

36-40: LGTM! Well-structured query configuration.

The implementation shows good practices:

  • Proper query key structure
  • Conditional execution using enabled
  • Type-safe path params

56-62: 🛠️ Refactor suggestion

Enhance error handling in upsertConfig mutation.

Current error handling only logs to console. Consider providing user feedback.

  const { mutate: upsertConfig } = useMutation({
    mutationFn: isNew
      ? mutate(routes.plugConfig.createPlugConfig)
      : mutate(routes.plugConfig.updatePlugConfig, { pathParams: { slug } }),
    onSuccess: () => navigate("/apps"),
-   onError: (error) => console.error("Error saving config:", error),
+   onError: (error) => {
+     console.error("Error saving config:", error);
+     // Use your app's toast/notification system
+     alert("Failed to save configuration. Please try again.");
+   },
  });

Likely invalid or redundant comment.


64-70: 🛠️ Refactor suggestion

Enhance error handling in deleteConfig mutation.

Current error handling only logs to console. Consider providing user feedback.

  const { mutate: deleteConfig } = useMutation({
    mutationFn: mutate(routes.plugConfig.deletePlugConfig, {
      pathParams: { slug },
    }),
    onSuccess: () => navigate("/apps"),
-   onError: (error) => console.error("Error deleting config:", error),
+   onError: (error) => {
+     console.error("Error deleting config:", error);
+     // Use your app's toast/notification system
+     alert("Failed to delete configuration. Please try again.");
+   },
  });

Likely invalid or redundant comment.


138-140: ⚠️ Potential issue

Add validation for JSON input.

The meta field accepts raw JSON input without validation, which could lead to runtime errors during submission.

  <Textarea
    value={config.meta}
    onChange={(e) => {
+     const newValue = e.target.value;
+     try {
+       // Validate JSON as user types
+       JSON.parse(newValue);
+       setConfig((prev) => ({ ...prev, meta: newValue }));
+     } catch (error) {
+       // Optional: Show validation error to user
+       console.error("Invalid JSON:", error);
+       // Still update the field to allow work in progress
+       setConfig((prev) => ({ ...prev, meta: newValue }));
+     }
    }}
    rows={10}
  />

Likely invalid or redundant comment.

@abhimanyurajeesh
Copy link
Contributor Author

@rithviknishad requesting for review 2 🙃

@rithviknishad
Copy link
Member

use this button for requesting reviews... easier to track that way

image

src/Utils/featureFlags.tsx Outdated Show resolved Hide resolved
src/Utils/featureFlags.tsx Outdated Show resolved Hide resolved
@abhimanyurajeesh
Copy link
Contributor Author

@rithviknishad sorry about requesting for review before syncing the changes.

@rithviknishad rithviknishad requested a review from bodhish January 14, 2025 07:32
@abhimanyurajeesh abhimanyurajeesh changed the title Refactor: Update feature flag handling and integrate tanstack's useQu… Removed unused feature flag handling and migrated to TanStack's query Jan 14, 2025
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.

our global error handler should take care of it btw.

src/pages/Apps/PlugConfigEdit.tsx Outdated Show resolved Hide resolved
src/pages/Apps/PlugConfigEdit.tsx Outdated Show resolved Hide resolved
@abhimanyurajeesh
Copy link
Contributor Author

Yap noted! made the changes.

@nihal467
Copy link
Member

LGTM

@nihal467 nihal467 added tested reviewed reviewed by a core member and removed needs testing labels Jan 15, 2025
@rithviknishad rithviknishad merged commit 31aac73 into ohcnetwork:develop Jan 15, 2025
20 checks passed
Copy link

@abhimanyurajeesh Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
reviewed reviewed by a core member tested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants