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 : Button Refreshes Entire Organizations #10978

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

Conversation

Jeffrin2005
Copy link
Contributor

@Jeffrin2005 Jeffrin2005 commented Mar 3, 2025

Proposed Changes

fix34.mp4

@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 the removal process with improved feedback: the removal button now displays a loading indicator and disables during processing, ensuring a smoother experience when managing organization removals.

@Jeffrin2005 Jeffrin2005 requested a review from a team as a code owner March 3, 2025 15:24
Copy link
Contributor

coderabbitai bot commented Mar 3, 2025

Walkthrough

The changes introduce a new state variable, removingOrgId, in the LinkDepartmentsSheet component to manage the organization removal process. The removeOrganization mutation no longer uses isPending to track loading states; instead, it relies on removingOrgId to control button states and display a loading spinner. This refactor simplifies mutation handling by removing the isRemoving state and enhances the UI's responsiveness to the removal operation's status.

Changes

File Change Summary
src/components/Patient/LinkDepartmentsSheet.tsx Added removingOrgId state variable to track organization removal. Updated removeOrganization mutation to eliminate isPending tracking. Adjusted logic to set and reset removingOrgId during the removal process.

Suggested labels

needs testing, needs review

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

In the meadow where code does play,
A rabbit hops with joy today.
With removingOrgId in the mix,
Our UI dances, smooth and slick!
🐇 Bugs be gone, let the changes sing,
Happy coding, let the springtime bring!

✨ 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 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 Mar 3, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 93214b2
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67c6924db803340008d8a017
😎 Deploy Preview https://deploy-preview-10978.preview.ohc.network
📱 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.

Comment on lines 223 to 231
variant="ghost"
size="icon"
onClick={() => removeOrganization(org.id)}
disabled={isRemoving}
disabled={removingOrgId === org.id}
>
{isRemoving ? (
{removingOrgId === org.id ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Trash2 className="h-4 w-4 text-destructive" />
Copy link
Member

Choose a reason for hiding this comment

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

i'd say wrap this button in a component and keep the useMutation there in that component, and use useMutation's isPending to show the loading state instead of creating a new state 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 (3)
src/components/Patient/LinkDepartmentsSheet.tsx (3)

100-131: Consider extracting the error handling logic to reduce duplication.

The error handling logic is duplicated between this mutation and the addOrganization mutation. This could be extracted into a reusable utility function to follow the DRY principle.

// Add a utility function at the top of the file
+function handleMutationError(error: any) {
+  const errorData = error.cause as { errors: { msg: string }[] };
+  errorData.errors.forEach((er) => {
+    toast.error(er.msg);
+  });
+}

// Then in the DeleteOrganizationButton component
 onError: (error) => {
-  const errorData = error.cause as { errors: { msg: string }[] };
-  errorData.errors.forEach((er) => {
-    toast.error(er.msg);
-  });
+  handleMutationError(error);
 },

133-146: Add accessibility attributes to the button.

Since the button only contains an icon, it should have an appropriate aria-label for screen readers.

 <Button
   variant="ghost"
   size="icon"
   onClick={() => removeOrganization(organizationId)}
   disabled={isPending}
+  aria-label={t("remove_organization")}
 >
   {isPending ? (
     <Loader2 className="h-4 w-4 animate-spin" />
   ) : (
     <Trash2 className="h-4 w-4 text-destructive" />
   )}
 </Button>

174-180: Refactor query invalidation for consistency.

The addOrganization mutation uses getInvalidateQueries, but the DeleteOrganizationButton uses getMutationParams(...).queryKey. For consistency, consider using the same approach for both.

onSuccess: () => {
-  const invalidateQueries = getInvalidateQueries(entityType, entityId);
-  queryClient.invalidateQueries({ queryKey: invalidateQueries });
+  const { queryKey } = getMutationParams(
+    entityType,
+    entityId,
+    facilityId,
+    true,
+  );
+  queryClient.invalidateQueries({ queryKey });
  toast.success("Organization added successfully");
  setSelectedOrg("");
  setOpen(false);
  onUpdate?.();
},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3c4278b and a37b980.

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

87-147: Well-implemented component extraction!

This is a great implementation of the component extraction approach. By moving the delete functionality into its own component:

  • The loading state is now properly managed with isPending from useMutation
  • The component is reusable and has a clear, focused responsibility
  • The UI feedback during deletion operations is improved with the loading spinner

This directly addresses the issue mentioned in the PR title about refreshing entire organizations, as the loading state is now localized to just the button being clicked.


245-251: Good implementation of component reuse!

Excellent use of the extracted component with all the necessary props passed correctly. The inclusion of the onSuccess callback to trigger the onUpdate function ensures that any parent components stay in sync with the changes.

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/components/Patient/LinkDepartmentsSheet.tsx (1)

92-119: Consider consistent loading state pattern across mutations.

While the removeOrganization mutation now uses organization-specific loading states, the addOrganization mutation still uses a global isAdding state. For consistency, you might want to apply the same pattern to both mutations.

-  const { mutate: addOrganization, isPending: isAdding } = useMutation({
+  const [addingOrg, setAddingOrg] = useState<boolean>(false);
+  const { mutate: addOrganization } = useMutation({
     mutationFn: (organizationId: string) => {
+      setAddingOrg(true);
       const { route, pathParams } = getMutationParams(
         entityType,
         entityId,
         facilityId,
         true,
       );
       // rest of the code...
     },
     onSuccess: () => {
       // existing code...
+      setAddingOrg(false);
     },
     onError: (error) => {
+      setAddingOrg(false);
       // existing error handling...
     },
   });

Then update the button:

-                disabled={!selectedOrg || isAdding}
+                disabled={!selectedOrg || addingOrg}
               >
-                {isAdding && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+                {addingOrg && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}

Also applies to: 120-153

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a37b980 and 93214b2.

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

90-90: Good addition of organization-specific loading state tracking.

This state variable provides granular control over loading indicators for each organization's removal button, a better approach than the previous global loading state.


120-120: Correctly removed the global isPending state tracking.

The change aligns with the new approach of tracking loading states at the individual organization level rather than globally.


122-122: Good implementation of loading state management.

Setting the removingOrgId at the start of the mutation properly identifies which organization is currently being processed.


143-143: Proper cleanup of loading state in both success and error paths.

The code correctly resets the removingOrgId state regardless of whether the operation succeeds or fails, ensuring the UI won't get stuck in a loading state.

Also applies to: 147-147


214-214: Improved UI feedback during organization removal.

The button now correctly:

  1. Disables only the specific organization being removed
  2. Shows a loading spinner only for the specific organization being removed
  3. Prevents multiple removal operations from being initiated simultaneously

This change directly addresses the issue described in the PR title by preventing the entire organization list from refreshing during removal operations.

Also applies to: 216-220


211-219: Consider alternative implementation approach for better maintainability.

In response to a previous review comment about wrapping the button in a component, I'd like to note that this is still a valid suggestion worth considering for future refactoring. A dedicated RemoveOrganizationButton component would improve:

  1. Code organization by encapsulating the removal functionality
  2. Reusability if this pattern is used elsewhere
  3. Testing by isolating the functionality

A component-based implementation might look like this:

// RemoveOrganizationButton.tsx
function RemoveOrganizationButton({ organizationId, onRemove, onSuccess, onError }) {
  const [isRemoving, setIsRemoving] = useState(false);
  
  const handleRemove = async () => {
    setIsRemoving(true);
    try {
      await onRemove(organizationId);
      onSuccess?.();
    } catch (error) {
      onError?.(error);
    } finally {
      setIsRemoving(false);
    }
  };
  
  return (
    <Button
      variant="ghost"
      size="icon"
      onClick={handleRemove}
      disabled={isRemoving}
    >
      {isRemoving ? (
        <Loader2 className="h-4 w-4 animate-spin" />
      ) : (
        <Trash2 className="h-4 w-4 text-destructive" />
      )}
    </Button>
  );
}

Then use it in the main component:

<RemoveOrganizationButton 
  organizationId={org.id}
  onRemove={removeOrganization}
  onSuccess={() => queryClient.invalidateQueries({ queryKey })}
  onError={(error) => {
    const errorData = error.cause as { errors: { msg: string }[] };
    errorData.errors.forEach((er) => {
      toast.error(er.msg);
    });
  }}
/>

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.

Delete Button Refreshes Entire Organizations
3 participants