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: toasts-not-dismissings #2304

Open
wants to merge 40 commits into
base: main
Choose a base branch
from

Conversation

AkshayBandi027
Copy link
Contributor

@AkshayBandi027 AkshayBandi027 commented Oct 10, 2024

What does this PR do?

Fixes #2194

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • go to dashboard/authorization/roles/[roleId]
  • updated the role

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Streamlined role and permission management with enhanced loading state and toast notifications for connect, disconnect, delete, and update actions.
    • Introduced visual feedback with a new icon for successful permission changes.
  • Bug Fixes

    • Resolved issues with loading toast notifications not dismissing correctly after role operations.

Copy link

changeset-bot bot commented Oct 10, 2024

⚠️ No Changeset found

Latest commit: 65203ad

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Oct 10, 2024

@AkshayBandi027 is attempting to deploy a commit to the Unkey Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 10, 2024

Warning

Rate limit exceeded

@chronark has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 39 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 38037ee and 65203ad.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes introduced in this pull request involve modifications to the RoleToggle, DeleteRole, UpdateRole, and PermissionToggle components. Each component now utilizes a new reference variable, loadingToastId, created with useRef, to manage the ID of loading toast notifications. The onMutate callbacks have been updated to store this ID, and the onSuccess and onError callbacks have been modified to dismiss the loading toast using this ID. Additionally, the useRef import statement has been added where it was previously missing.

Changes

File Path Change Summary
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/role-toggle.tsx, apps/dashboard/app/(app)/authorization/roles/[roleId]/delete-role.tsx, apps/dashboard/app/(app)/authorization/roles/[roleId]/update-role.tsx, apps/dashboard/app/(app)/authorization/roles/[roleId]/permission-toggle.tsx Added loadingToastId using useRef to manage loading toast notifications; updated mutation callbacks to handle toast dismissal.

Assessment against linked issues

Objective Addressed Explanation
Ensure all toast notifications hide after completion (Issue #2194)

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
Contributor

github-actions bot commented Oct 10, 2024

Thank you for following the naming conventions for pull request titles! 🙏

Copy link

vercel bot commented Oct 10, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 14, 2024 5:29pm

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 (6)
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/role-toggle.tsx (3)

17-17: LGTM: loadingToastId ref added correctly.

The useRef hook is appropriately used to manage the loading toast ID across re-renders. This change aligns well with the PR objective of fixing toast dismissal issues.

Consider adding a brief comment explaining the purpose of this ref, e.g.:

// Ref to store the ID of the current loading toast for proper dismissal
const loadingToastId = useRef<string | number | null>(null);

37-38: LGTM: Toast dismissal logic implemented correctly.

The toast dismissal logic has been properly implemented in both the onSuccess and onError callbacks. This directly addresses the toast dismissal issue mentioned in the PR objective.

Consider extracting the dismissal logic into a separate function to reduce code duplication:

const dismissLoadingToast = () => {
  toast.dismiss(loadingToastId.current!);
  loadingToastId.current = null;
};

// Then use it in both callbacks:
onSuccess: () => {
  // ... existing success logic
  dismissLoadingToast();
},
onError: (err) => {
  // ... existing error logic
  dismissLoadingToast();
},

Also applies to: 43-44


66-67: LGTM: Consistent toast dismissal logic in disconnect mutation.

The toast dismissal logic in the disconnect mutation's onSuccess and onError callbacks is consistent with the connect mutation, completing the fix for both operations.

As suggested earlier, consider extracting the dismissal logic into a shared function to reduce code duplication across both mutations:

const dismissLoadingToast = () => {
  toast.dismiss(loadingToastId.current!);
  loadingToastId.current = null;
};

// Use in all four callbacks (connect.onSuccess, connect.onError, disconnect.onSuccess, disconnect.onError)

This refactoring would improve code maintainability and reduce the likelihood of inconsistencies in future updates.

Also applies to: 72-73

apps/dashboard/app/(app)/authorization/roles/[roleId]/delete-role.tsx (1)

63-64: LGTM with a small suggestion: Update onSuccess and onError callbacks.

The changes in both callbacks correctly dismiss the loading toast using the stored ID and reset the ref. This ensures proper toast lifecycle management in both success and error scenarios.

However, I suggest a small improvement for safer null checking:

// In both onSuccess and onError callbacks
if (loadingToastId.current !== null) {
  toast.dismiss(loadingToastId.current);
  loadingToastId.current = null;
}

This change will prevent potential runtime errors if loadingToastId.current is unexpectedly null.

Also applies to: 69-70

apps/dashboard/app/(app)/authorization/roles/[roleId]/update-role.tsx (2)

47-47: LGTM: loadingToastId ref added correctly.

The use of useRef for loadingToastId is appropriate for persisting the toast ID across re-renders. The type annotation is comprehensive, covering all possible return types from the toast library.

Consider adding a comment explaining the purpose of this ref, e.g.:

// Ref to store the ID of the loading toast for proper dismissal
const loadingToastId = useRef<string | number | null>(null);

This would enhance code readability and maintainability.


64-65: LGTM: Toast dismissal logic improved, with a minor suggestion.

The loading toast is now properly dismissed using the stored ID, and the ref is correctly reset to null afterwards. This ensures proper toast management regardless of the mutation outcome.

Consider adding a null check before dismissing the toast to make the code more robust:

if (loadingToastId.current !== null) {
  toast.dismiss(loadingToastId.current);
  loadingToastId.current = null;
}

This change would prevent potential runtime errors if loadingToastId.current is unexpectedly null.

Also applies to: 71-72

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c948512 and 646f6f9.

📒 Files selected for processing (3)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/role-toggle.tsx (5 hunks)
  • apps/dashboard/app/(app)/authorization/roles/[roleId]/delete-role.tsx (3 hunks)
  • apps/dashboard/app/(app)/authorization/roles/[roleId]/update-role.tsx (3 hunks)
🧰 Additional context used
🔇 Additional comments (11)
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/role-toggle.tsx (4)

8-8: LGTM: Import statement updated correctly.

The import statement has been properly updated to include useRef, which is necessary for the changes made in the component.


23-25: LGTM: Toast ID properly stored in ref.

The loading toast ID is now correctly stored in the loadingToastId ref. This change is crucial for proper toast dismissal later, addressing the main objective of the PR.


53-54: LGTM: Consistent implementation in disconnect mutation.

The changes in the disconnect mutation's onMutate callback are consistent with those in the connect mutation, ensuring proper toast management for both operations.


Line range hint 1-94: Overall: Great implementation addressing toast dismissal issues.

The changes in this file effectively solve the problem of toasts not being dismissed properly. The implementation is consistent across both connect and disconnect operations, using a useRef hook to manage the loading toast ID. This approach ensures that toasts are correctly dismissed in both success and error scenarios.

Key points:

  1. The loadingToastId ref is correctly implemented and used.
  2. Toast creation and dismissal logic is consistently applied in all relevant callbacks.
  3. The changes align well with the PR objective of fixing toast dismissal issues.

Suggestions for improvement:

  1. Consider adding a brief comment explaining the purpose of the loadingToastId ref.
  2. Extract the toast dismissal logic into a shared function to reduce code duplication and improve maintainability.

Overall, this is a solid implementation that effectively addresses the issue at hand.

apps/dashboard/app/(app)/authorization/roles/[roleId]/delete-role.tsx (4)

28-28: LGTM: Import statement updated correctly.

The useRef hook has been appropriately added to the import statement from 'react'. This change is consistent with its usage in the component and follows the convention of grouping related imports.


42-42: LGTM: loadingToastId ref added correctly.

The loadingToastId ref is well-implemented using useRef. The type annotation <string | number | null> appropriately covers all possible return types from the toast library. Initializing with null is a good practice for refs that may not have an initial value.


58-59: LGTM: onMutate callback updated to store toast ID.

The onMutate callback has been correctly updated to store the loading toast ID in the loadingToastId ref. This change is crucial for properly managing the toast lifecycle, allowing the ID to persist across re-renders and be accessed in other callbacks.


Line range hint 28-70: Overall: Great improvements in toast notification handling!

The changes in this file consistently implement a new approach to managing toast notifications using a ref. This improves the handling of loading states and ensures proper lifecycle management of toast notifications. The implementation aligns well with React best practices and enhances the overall reliability of the component.

A minor suggestion was made for safer null checking in the onSuccess and onError callbacks, but overall, these changes represent a significant improvement in the component's functionality.

apps/dashboard/app/(app)/authorization/roles/[roleId]/update-role.tsx (3)

30-30: LGTM: Import statement updated correctly.

The addition of useRef to the import statement is consistent with its usage in the component logic for managing the loadingToastId.


59-60: LGTM: Loading toast ID properly stored.

The loading toast ID is correctly stored in loadingToastId.current, allowing for proper management of the toast throughout the component lifecycle.


Line range hint 1-153: Summary: PR successfully addresses toast dismissal issue.

This PR effectively resolves the issue of toasts not being dismissed as expected. The implementation of useRef to manage the loading toast ID ensures proper lifecycle management of the toast notifications. These changes align well with the PR objective of fixing the "toasts-not-dismissing" issue.

To fully meet the PR objectives:

  1. Ensure that you've linked this PR to the corresponding issue for tracking purposes.
  2. Confirm that you've tested the changes by navigating to the dashboard and updating a role at the specified URL path: dashboard/authorization/roles/[roleId].

To verify the changes, please run the following script:

This script will help ensure that the toast dismissal logic has been implemented consistently across all relevant files in the project.

✅ Verification successful

Verified: The toast dismissal logic has been consistently implemented across all relevant TypeScript files.

The verification scripts confirmed the presence of loadingToastId usage, toast.dismiss(loadingToastId.current!) calls, and the resetting of loadingToastId.current = null in the following files:

  • apps/dashboard/app/(app)/authorization/roles/[roleId]/update-role.tsx
  • apps/dashboard/app/(app)/authorization/roles/[roleId]/delete-role.tsx
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/role-toggle.tsx

These changes effectively resolve the issue of toasts not being dismissed as expected, aligning with the PR's objective.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the toast dismissal logic is implemented consistently across all relevant files.

# Test: Search for loadingToastId usage
echo "Checking for loadingToastId usage:"
rg --type typescript 'const loadingToastId = useRef<string \| number \| null>\(null\)'

# Test: Search for toast.dismiss usage with loadingToastId
echo "Checking for toast dismissal logic:"
rg --type typescript 'toast\.dismiss\(loadingToastId\.current'

# Test: Search for loadingToastId reset to null
echo "Checking for loadingToastId reset:"
rg --type typescript 'loadingToastId\.current = null'

Length of output: 553


Script:

#!/bin/bash
# Description: Verify that the toast dismissal logic is implemented consistently across all relevant TypeScript files.

# Test: Search for loadingToastId usage in .ts and .tsx files
echo "Checking for loadingToastId usage in TypeScript files:"
rg 'const loadingToastId = useRef<string \| number \| null>\(null\)' --type-add 'typescript:*.ts,*.tsx' --type typescript

# Test: Search for toast.dismiss usage with loadingToastId in .ts and .tsx files
echo "Checking for toast dismissal logic in TypeScript files:"
rg 'toast\.dismiss\(loadingToastId\.current' --type-add 'typescript:*.ts,*.tsx' --type typescript

# Test: Search for loadingToastId reset to null in .ts and .tsx files
echo "Checking for loadingToastId reset in TypeScript files:"
rg 'loadingToastId\.current = null' --type-add 'typescript:*.ts,*.tsx' --type typescript

Length of output: 1120


Script:

#!/bin/bash
# Description: Verify that the toast dismissal logic is implemented consistently across all relevant TypeScript files.

# Test: Search for loadingToastId usage in .ts and .tsx files
echo "Checking for loadingToastId usage in .ts and .tsx files:"
rg 'const loadingToastId = useRef<string \| number \| null>\(null\)' --glob '*.ts' --glob '*.tsx'

# Test: Search for toast.dismiss usage with loadingToastId in .ts and .tsx files
echo "Checking for toast dismissal logic in .ts and .tsx files:"
rg 'toast\.dismiss\(loadingToastId\.current' --glob '*.ts' --glob '*.tsx'

# Test: Search for loadingToastId reset to null in .ts and .tsx files
echo "Checking for loadingToastId reset in .ts and .tsx files:"
rg 'loadingToastId\.current = null' --glob '*.ts' --glob '*.tsx'

Length of output: 2867

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 (5)
apps/dashboard/app/(app)/authorization/roles/[roleId]/permission-toggle.tsx (5)

19-19: LGTM: useRef for toast ID management.

The addition of loadingToastId using useRef is a good approach for managing the toast ID across re-renders. The type annotation is comprehensive, covering all possible return types from the toast library.

Consider using a more specific name like loadingToastIdRef to clearly indicate that this is a ref, following common React naming conventions for refs.


36-37: LGTM with suggestion: Toast dismissal in onSuccess.

The changes correctly dismiss the loading toast and reset the ref. This addresses the issue of toasts not dismissing after the action completes.

Consider adding a null check before dismissing the toast to handle potential edge cases:

if (loadingToastId.current !== null) {
  toast.dismiss(loadingToastId.current);
  loadingToastId.current = null;
}

This approach would be safer and prevent potential runtime errors if the ID is unexpectedly null.


43-44: LGTM: Consistent toast dismissal in onError.

The changes in the onError callback mirror those in onSuccess, ensuring consistent behavior regardless of the mutation outcome. This contributes to resolving the issue of toasts not dismissing properly.

Apply the same null check suggestion as mentioned in the onSuccess callback to handle potential edge cases safely.


65-66: LGTM: Consistent toast management in disconnect onSuccess.

The changes in the disconnect mutation's onSuccess callback are consistent with the connect mutation, ensuring uniform behavior across different actions.

Apply the same null check suggestion as mentioned in the previous callbacks to handle potential edge cases safely.


71-72: LGTM with minor syntax note: Consistent toast management in disconnect onError.

The changes in the disconnect mutation's onError callback maintain consistency with other callbacks, contributing to the overall fix for the toast dismissal issue.

Apply the same null check suggestion as mentioned in the previous callbacks to handle potential edge cases safely.

Add a semicolon at the end of line 71 for consistency with the coding style in the rest of the file:

toast.dismiss(loadingToastId.current!);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 646f6f9 and 4cfef40.

📒 Files selected for processing (1)
  • apps/dashboard/app/(app)/authorization/roles/[roleId]/permission-toggle.tsx (4 hunks)
🧰 Additional context used
🔇 Additional comments (3)
apps/dashboard/app/(app)/authorization/roles/[roleId]/permission-toggle.tsx (3)

8-8: LGTM: Import statement updated correctly.

The addition of useRef to the import statement is appropriate for the new functionality introduced in the component.


23-24: LGTM: Proper toast ID management in onMutate.

The changes correctly store the loading toast ID in the ref, allowing for its retrieval and dismissal in other lifecycle methods. This implementation aligns with the PR objective of fixing the issue with toasts not dismissing properly.


Line range hint 1-93: Summary: Effective implementation of toast dismissal with minor improvement suggestions.

The changes in this file successfully address the issue of toasts not dismissing properly, as outlined in the PR objectives. The implementation is consistent across different scenarios (success and error cases for both connect and disconnect mutations), ensuring that loading toasts are properly managed throughout the component's lifecycle.

Key points:

  1. The use of useRef for managing toast IDs is appropriate and effective.
  2. Toast dismissal is consistently implemented in all relevant callbacks.
  3. The changes align well with the PR's goal of fixing the issue described in [🕹️] Some toasts keep showing as loading even when they finish #2194.

Suggestions for further improvement:

  1. Consider using a more specific naming convention for the ref (e.g., loadingToastIdRef).
  2. Implement null checks before dismissing toasts to handle potential edge cases safely.
  3. Ensure consistent use of semicolons at the end of statements.

Overall, these changes significantly improve the user experience by ensuring that toast notifications are properly dismissed after actions are completed.

@chronark
Copy link
Collaborator

chronark commented Oct 12, 2024

I think the proper way to do this would be using a promise, like the author of the library intended, can we try that?
https://sonner.emilkowal.ski/toast#updating-toasts

@chronark chronark self-assigned this Oct 12, 2024
@AkshayBandi027
Copy link
Contributor Author

I think the proper way to do this would be using a promise, like the author of the library intended, can we try that? https://sonner.emilkowal.ski/toast#promise

Sure !!

perkinsjr and others added 13 commits October 14, 2024 22:04
* fixed bucket caching issue for multiple keys on audit log.

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
* removed the wrong commits pushed with this PR

* adding roadmap after other info

---------

Co-authored-by: Meg Stepp <mcstepp@users.noreply.github.com>
Followed unkey on Twitter

Co-authored-by: Andreas Thomas <dev@chronark.com>
* fix: transaction ...: in use: for query
- Fixes unkeyed#2197
- The error is caused by the cache revalidation happening in the background, so we have a racecondition with the other queries we are running in the insertGenericAuditLogs function

* docs: explain for future self

* fix: another racecondition
also bulk insert auditLogs and auditLogTargets

* [autofix.ci] apply automated fixes

---------

Co-authored-by: chronark <dev@chronark.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Chirag8023 and others added 20 commits October 14, 2024 22:04
* Update 3_follow_the_unkey_x_account.md

* Update 3_follow_the_unkey_x_account.md

---------

Co-authored-by: Andreas Thomas <dev@chronark.com>
- add hover effect to analytics bento removing gradient background
- make copy code button sticky to top-right corner
- impl independent vertical scrolls for language switcher and code editor
…nkeyed#2255)

Bumps @content-collections/core from 0.6.2 to 0.7.2.

---
updated-dependencies:
- dependency-name: "@content-collections/core"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
…#2316)

* fix: reset input fields in API delete dialog after reopening

* refactor: remove unnecessary useEffect and utilize existing onOpenChange function for dialog

* refactor: removed unused imports
Added name to the followed list.

Co-authored-by: Andreas Thomas <dev@chronark.com>
* Feat: Followed Unkey on X

* Feat: Followed Unkey on Twitter

---------

Co-authored-by: Andreas Thomas <dev@chronark.com>
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: 9

🧹 Outside diff range and nitpick comments (1)
apps/dashboard/app/(app)/authorization/roles/[roleId]/permission-toggle.tsx (1)

93-100: Use onChange instead of onClick for the Checkbox component

The Checkbox component should use the onChange event handler to ensure proper accessibility and handling of user interactions, especially for keyboard navigation and assistive technologies.

Apply this change:

 <Checkbox
   checked={optimisticChecked}
-  onClick={() => {
+  onChange={() => {
     if (optimisticChecked) {
       handleDisconnect(roleId, permissionId);
     } else {
       handleConnect(roleId, permissionId);
     }
   }}
 />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4cfef40 and 38037ee.

📒 Files selected for processing (4)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/role-toggle.tsx (3 hunks)
  • apps/dashboard/app/(app)/authorization/roles/[roleId]/delete-role.tsx (1 hunks)
  • apps/dashboard/app/(app)/authorization/roles/[roleId]/permission-toggle.tsx (3 hunks)
  • apps/dashboard/app/(app)/authorization/roles/[roleId]/update-role.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/dashboard/app/(app)/authorization/roles/[roleId]/delete-role.tsx
  • apps/dashboard/app/(app)/authorization/roles/[roleId]/update-role.tsx
🧰 Additional context used
🪛 Biome
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/role-toggle.tsx

[error] 44-47: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)


[error] 72-75: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

apps/dashboard/app/(app)/authorization/roles/[roleId]/permission-toggle.tsx

[error] 47-50: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)


[error] 75-78: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

🔇 Additional comments (2)
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/role-toggle.tsx (2)

6-6: Imports added for necessary icons

The CircleCheck and Loader2 icons are imported correctly from lucide-react.


93-95: Toggle action logic is properly implemented

The onClick handler correctly calls handleDisconnect or handleConnect based on the optimisticChecked state.

Comment on lines +33 to +35
const handleConnect = async (roleId: string, permissionId: string) => {
setOptimisticChecked(true);
toast.promise(connect.mutateAsync({ roleId, permissionId }), {
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 14, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Revert optimistic UI update if the mutation fails

In handleConnect, you're setting optimisticChecked to true before the mutation completes. If the mutation fails, the checkbox remains checked, which doesn't reflect the actual state.

Consider reverting optimisticChecked in the error handler to ensure UI consistency.

Apply this change:

 const handleConnect = async (roleId: string, permissionId: string) => {
     setOptimisticChecked(true);
     toast.promise(connect.mutateAsync({ roleId, permissionId }), {
       loading: "Adding Permission ...",
       success: () => (
         // success handling
       ),
       error: (error) => {
+        setOptimisticChecked(false);
         `${error.message || "An error occurred while adding the permission."}`
       },
     });
   };

Similarly, in handleDisconnect, ensure the state is reverted on error.

 const handleDisconnect = async (roleId: string, permissionId: string) => {
     setOptimisticChecked(false);
     toast.promise(disconnect.mutateAsync({ roleId, permissionId }), {
       loading: "Removing Permission ...",
       success: () => (
         // success handling
       ),
       error: (error) => {
+        setOptimisticChecked(true);
         `${error.message || "An error occurred while removing the permission."}`
       },
     });
   };

Also applies to: 57-58

Copy link
Collaborator

Choose a reason for hiding this comment

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

makes sense I think

Copy link
Contributor

Choose a reason for hiding this comment

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

@chronark, glad the suggestion makes sense! Let me know if you have any questions or need further assistance.

(_/)
(•ᴥ•)
/ ❤️


const handleDisconnect = async (roleId: string, permissionId: string) => {
setOptimisticChecked(false);
toast.error("My error toast");
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 14, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove placeholder error toast message

At line 62, there's a call to toast.error("My error toast"); which appears to be a placeholder or debug message. This may confuse users if left in production.

Consider removing or replacing it with a meaningful error message.

Apply this diff to fix the issue:

-    toast.error("My error toast");
📝 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
toast.error("My error toast");

Copy link
Collaborator

Choose a reason for hiding this comment

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

please check this @AkshayBandi027

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!

Comment on lines +75 to +78
<button
onClick={() => connect.mutate({ roleId, permissionId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add explicit type="button" to the <button> element to prevent unintended form submissions

Similar to the previous instance, ensure the type attribute is set to "button" to avoid unintended form behavior.

Apply this diff to fix the issue:

             <button
+              type="button"
               onClick={() => connect.mutate({ roleId, permissionId })}
               className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
             >
📝 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
<button
onClick={() => connect.mutate({ roleId, permissionId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
<button
type="button"
onClick={() => connect.mutate({ roleId, permissionId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
🧰 Tools
🪛 Biome

[error] 75-78: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

Comment on lines +47 to +50
<button
onClick={() => disconnect.mutate({ roleId, permissionId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add explicit type="button" to the <button> element to prevent unintended form submissions

The button element defaults to type="submit" if no type is specified, which can cause unintended form submissions when the button is inside a form. To prevent this, explicitly set the type attribute to "button".

Apply this diff to fix the issue:

             <button
+              type="button"
               onClick={() => disconnect.mutate({ roleId, permissionId })}
               className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
             >
📝 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
<button
onClick={() => disconnect.mutate({ roleId, permissionId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
<button
type="button"
onClick={() => disconnect.mutate({ roleId, permissionId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
🧰 Tools
🪛 Biome

[error] 47-50: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

</div>
</div>
),
error: (error) => `${error.message || "An error occurred while adding the Role ."}`,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct error message formatting

Remove the extra space before the period and use consistent capitalization in the error message.

Apply this diff to fix the error message:

-      error: (error) => `${error.message || "An error occurred while adding the Role ."}`,
+      error: (error) => `${error.message || "An error occurred while adding the role."}`,
📝 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
error: (error) => `${error.message || "An error occurred while adding the Role ."}`,
error: (error) => `${error.message || "An error occurred while adding the role."}`,

Comment on lines +72 to +75
<button
onClick={() => connect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add explicit type attribute to the <button> element

Similarly, the <button> element here should have an explicit type attribute to prevent default form submission behavior. Add type="button".

Apply this diff to fix the issue:

 <button
+  type="button"
   onClick={() => connect.mutate({ roleId, keyId })}
   className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
 >
📝 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
<button
onClick={() => connect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
<button
type="button"
onClick={() => connect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
🧰 Tools
🪛 Biome

[error] 72-75: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

Comment on lines +44 to +47
<button
onClick={() => disconnect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add explicit type attribute to the <button> element

The <button> element should have an explicit type attribute to prevent unintended form submissions when used inside a <form>. Add type="button" to specify the button's behavior.

Apply this diff to fix the issue:

 <button
+  type="button"
   onClick={() => disconnect.mutate({ roleId, keyId })}
   className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
 >
📝 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
<button
onClick={() => disconnect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
<button
type="button"
onClick={() => disconnect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
🧰 Tools
🪛 Biome

[error] 44-47: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

Comment on lines +72 to +77
<button
onClick={() => connect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
Undo
</button>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update state when 'Undo' is clicked to maintain UI consistency

In this instance, clicking the 'Undo' button does not update the optimisticChecked state. To keep the UI in sync, update optimisticChecked after the mutation.

Apply this diff to update the state:

 <button
   type="button"
-  onClick={() => connect.mutate({ roleId, keyId })}
+  onClick={() => {
+    connect.mutate({ roleId, keyId });
+    setOptimisticChecked(true);
+  }}
   className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
 >
📝 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
<button
onClick={() => connect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
Undo
</button>
<button
type="button"
onClick={() => {
connect.mutate({ roleId, keyId });
setOptimisticChecked(true);
}}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
Undo
</button>
🧰 Tools
🪛 Biome

[error] 72-75: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

Comment on lines +44 to +49
<button
onClick={() => disconnect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
Undo
</button>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update state when 'Undo' is clicked to maintain UI consistency

When the 'Undo' button is clicked, the optimisticChecked state is not updated. This may cause the checkbox to display an incorrect state. Update optimisticChecked to ensure the UI reflects the actual state.

Apply this diff to update the state:

 <button
   type="button"
-  onClick={() => disconnect.mutate({ roleId, keyId })}
+  onClick={() => {
+    disconnect.mutate({ roleId, keyId });
+    setOptimisticChecked(false);
+  }}
   className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
 >
📝 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
<button
onClick={() => disconnect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
Undo
</button>
<button
type="button"
onClick={() => {
disconnect.mutate({ roleId, keyId });
setOptimisticChecked(false);
}}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
>
Undo
</button>
🧰 Tools
🪛 Biome

[error] 44-47: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

setOptimisticChecked(true);
toast.promise(connect.mutateAsync({ roleId, keyId }), {
loading: "Adding Role ...",
success: () => (
Copy link
Collaborator

Choose a reason for hiding this comment

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

why are we doing custom components here?

the toast already has a way to display an action
https://sonner.emilkowal.ski/toast#action

<div>
<button
onClick={() => disconnect.mutate({ roleId, keyId })}
className="bg-[#2c2c2c] text-white px-[4px] py-[2px] rounded hover:bg-[#3c3c3c] transition-colors"
Copy link
Collaborator

Choose a reason for hiding this comment

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

don't hardcode colors please

Copy link
Collaborator

@chronark chronark left a comment

Choose a reason for hiding this comment

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

see comments

@chronark chronark added the Changes Requested Waiting for a contributor to address feedback label Oct 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Changes Requested Waiting for a contributor to address feedback
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[🕹️] Some toasts keep showing as loading even when they finish