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: improved error handling and fixed loading state on sign-in page #701

Merged
merged 1 commit into from
Nov 15, 2024

Conversation

FleetAdmiralJakob
Copy link
Owner

@FleetAdmiralJakob FleetAdmiralJakob commented Nov 15, 2024

closes #686 and closes #667

Summary by CodeRabbit

  • New Features

    • Enhanced error handling during the sign-in process with specific messages for various scenarios.
    • Added a button to sign out and a link to return to the home page when a session already exists.
  • Improvements

    • Improved loading state management for a smoother user experience.
    • Updated rendering of error messages for better semantic structure.

Copy link

vercel bot commented Nov 15, 2024

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

Name Status Preview Comments Updated (UTC)
chat-io ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 15, 2024 0:36am

Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

Walkthrough

The changes made to the SignInForm component in signin-form.tsx include updates to the import statements, enhanced error handling within the onSubmit function, and adjustments to the loading state management. The error handling now differentiates between various error types, providing specific messages and actions for users. Additionally, the form's loading state is more effectively managed, affecting the button's disabled state and the semantic structure of error message rendering.

Changes

File Change Summary
src/app/(auth)/sign-in/signin-form.tsx Updated imports to include useAuth and isClerkAPIResponseError. Adjusted formIsLoading state management. Enhanced error handling in onSubmit with specific messages for various errors. Changed error message rendering from span to div.

Assessment against linked issues

Objective Addressed Explanation
Improve error handling on sign-in page (#686)
Fix loading state on sign-in page (#667)

Poem

🐰 In the meadow where bunnies play,
A form was fixed in a splendid way.
Errors caught with care and grace,
Loading states now keep the pace.
Hooray for sign-ins, smooth and bright,
Bouncing forward, all feels right! 🌼


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

@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

🧹 Outside diff range and nitpick comments (3)
src/app/(auth)/sign-in/signin-form.tsx (3)

68-70: Refactor wholeFormError State to Improve Maintainability

The state variable wholeFormError is defined as null | string | ReactNode, which mixes data types (strings and JSX elements). This can make the code harder to maintain and debug. It's generally advisable to keep state variables data-focused (e.g., strings or objects) and handle rendering logic separately in the JSX.

Consider keeping wholeFormError as a string | null and using conditional rendering in the JSX to handle cases where you need to include interactive elements like buttons or links.

Example refactor:

- const [wholeFormError, setWholeFormError] = useState<
-   null | string | ReactNode
- >(null);
+ const [wholeFormError, setWholeFormError] = useState<string | null>(null);
+ const [showSignOutOption, setShowSignOutOption] = useState(false);

Update the error handling logic:

if (isClerkAPIResponseError(err)) {
  if (err.errors.some((err) => err.code === "session_exists")) {
-   setWholeFormError(
-     <div>
-       You are already signed in. Please{" "}
-       <button className="underline" onMouseDown={() => signOut()}>
-         sign out
-       </button>{" "}
-       before signing in again. Alternatively you can go back to the{" "}
-       <Link className="underline" href="/chats">
-         home page
-       </Link>
-       .
-     </div>,
-   );
+   setWholeFormError("You are already signed in. Please sign out before signing in again.");
+   setShowSignOutOption(true);
  }

And modify the JSX rendering:

{wholeFormError && (
  <>
    <br />
    <div className="text-sm font-medium text-destructive">
      {wholeFormError}
+     {showSignOutOption && (
+       <>
+         {" "}
+         <button className="underline" onClick={async () => await signOut()}>
+           sign out
+         </button>
+         {" "}before signing in again. Alternatively, you can go back to the{" "}
+         <Link className="underline" href="/chats">
+           home page
+         </Link>
+         .
+       </>
+     )}
    </div>
  </>
)}

This approach separates data from presentation, enhancing maintainability.


64-64: Ensure Proper Handling of Asynchronous signOut Function

The signOut function may return a promise. If it does, consider handling it asynchronously to ensure any necessary clean-up or state updates occur after sign-out completes.

Modify the onClick handler to handle the promise:

- <button className="underline" onClick={() => signOut()}>
+ <button
+   className="underline"
+   onClick={async () => {
+     await signOut();
+     // Add any additional logic here if needed
+   }}
+ >

107-142: Consider Logging Unexpected Errors for Better Debugging

In the catch block, if the error is not a ClerkAPIResponseError, the code sets a generic error message but does not log the error details. Logging unexpected errors can help in diagnosing issues during development and monitoring in production.

Add a console error to log unexpected errors:

} else {
  setWholeFormError("Something went wrong. Please try again.");
+ console.error("Unexpected error during sign-in:", err);
}

Ensure that sensitive information is not logged in production environments.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6531749 and 563aa4a.

📒 Files selected for processing (1)
  • src/app/(auth)/sign-in/signin-form.tsx (6 hunks)
🔇 Additional comments (1)
src/app/(auth)/sign-in/signin-form.tsx (1)

Line range hint 235-248: Enhanced Loading State Handling and User Feedback

The changes to the submit button correctly handle the loading state by disabling the button and providing visual feedback with a spinner. This improves the user experience by preventing multiple submissions and indicating that the form is processing.

// "You are already signed in. Please sign out before signing in again.",
<div>
You are already signed in. Please{" "}
<button className="underline" onMouseDown={() => signOut()}>
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 15, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use onClick Instead of onMouseDown for Button Interaction

Using onMouseDown for the "sign out" button may not capture all user interactions, especially for users navigating via keyboard or assistive technologies. It's more conventional and accessible to use onClick to handle button interactions.

Apply this change to improve accessibility:

- <button className="underline" onMouseDown={() => signOut()}>
+ <button className="underline" onClick={() => signOut()}>
📝 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 className="underline" onMouseDown={() => signOut()}>
<button className="underline" onClick={() => signOut()}>

Copy link
Owner Author

Choose a reason for hiding this comment

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

Act on press

This is a UI design hill I will die on, and it dismays me how often and hard I have had to fight for it.

Almost all interaction methods have a “press” and “release” event associated with them. Whenever possible, you should “do the thing” when you get the press event instead of waiting for the release event, because it makes the interaction feel substantially more responsive, and it reduces user errors by not allowing the focus to slide out of the hot box between press and release.

Even a “ballistic tap”, where your finger is intentionally bouncing off the button or touch surface, involves several tens of milliseconds delay between the press and release, and most button presses have well over a hundred ms dwell time. There is a delight in interfaces that feel like they respond instantly to your wishes, and the benefit to every single user is often more important than additional niche features.

Game developers, with simple UI toolkits, tend to get this right more often, but “sophisticated” app designers will often fight hard against it because it is mostly incompatible with options like interactive touch scrolling views, long press menus, and drag and drop.

Being able to drag scroll a web page or view with interactive controls in it is here to stay, and nets out way better than having to use a separate scroll bar, but there are still tons of fixed position controls that should act on press, and it is good UI design to favor them when possible.

In the early days of mobile VR, the system keyboard was a dedicated little OpenGL app that responded instantly. With full internationalization it became prudent to turn it into a conventional Android app, but the default act-on-release button behavior made it feel noticeably crappier. The design team resisted a push to change it, and insisted on commissioning a user study, which is a corporate politics ploy to bury something. I was irritated at how they tried to use leading questions and tasks, but It still came back one of the clearest slam-dunks I have seen for user testing – objectively less typos, expressed preference, and interview comments about the act-on-press version feeling “crisper” and “more responsive”.

So, I won that one, but the remaining times I brought it up for other interfaces, I did not, and you still see act-on-release throughout the Meta VR system interfaces.

Copy link
Contributor

Choose a reason for hiding this comment

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

@FleetAdmiralJakob, thank you for sharing your insights on acting on press events. I'll keep this in mind for future reviews.

(´•ω•̥`)


✏️ Learnings added
Learnt from: FleetAdmiralJakob
PR: FleetAdmiralJakob/chat-io#701
File: src/app/(auth)/sign-in/signin-form.tsx:114-114
Timestamp: 2024-11-15T12:50:23.964Z
Learning: In this codebase, prefer using `onMouseDown` over `onClick` for button interactions to act on press events, enhancing responsiveness and user experience.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@FleetAdmiralJakob FleetAdmiralJakob merged commit e581ead into main Nov 15, 2024
8 checks passed
@FleetAdmiralJakob FleetAdmiralJakob deleted the improved-sign-in-page branch November 25, 2024 12:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Error handling on sign-in page Loading state on sign-in page
1 participant