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: OAuth Button Loader State Not Reset on Browser Back Navigation. #2568

Merged
merged 1 commit into from
Oct 28, 2024

Conversation

Srayash
Copy link
Contributor

@Srayash Srayash commented Oct 25, 2024

What does this PR do?

set Loader state to null after the await is over.
Fixes #2536

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?

  • Navigate to the OAuth sign-in/sign-up page.
  • Click on the GitHub or Google sign-in button (the loading state is triggered).
  • Press the browser back button before completing the OAuth process.
  • Observe that the button no longer shows the loading spinner.

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

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features
    • Improved loading state management during OAuth sign-in and sign-up processes for a more accurate user experience.
  • Bug Fixes
    • Enhanced error handling to ensure proper notifications are displayed upon authentication errors.

Copy link

changeset-bot bot commented Oct 25, 2024

⚠️ No Changeset found

Latest commit: c351091

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.

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

@CLAassistant
Copy link

CLAassistant commented Oct 25, 2024

CLA assistant check
All committers have signed the CLA.

Copy link

vercel bot commented Oct 25, 2024

@Srayash 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 25, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve modifications to the oauthSignIn function in both the OAuthSignIn and OAuthSignUp components. Specifically, a line was added to reset the isLoading state to null after initiating the authentication process with signIn.authenticateWithRedirect and signUp.authenticateWithRedirect, respectively. This adjustment aims to ensure that the loading state does not persist when the user navigates back during the OAuth process. The overall structure and error handling within the components remain unchanged.

Changes

File Path Change Summary
apps/dashboard/app/auth/sign-in/oauth-signin.tsx Modified oauthSignIn to reset isLoading state to null after initiating authentication.
apps/dashboard/app/auth/sign-up/oauth-signup.tsx Modified oauthSignUp to reset isLoading state to null after initiating authentication.

Assessment against linked issues

Objective Addressed Explanation
Reset loading state on browser back navigation (Issue #2536)

Possibly related PRs

  • fix(dashboard): hydration warnings #2253: The changes in this PR involve modifications to the oauthSignIn function in the OAuthSignUp component, which also includes a similar adjustment to the isLoading state after an authentication call, indicating a direct relationship in handling loading states during authentication processes.

Suggested labels

joystick: 150 points, hacktoberfest

Suggested reviewers

  • mcstepp
  • chronark
  • perkinsjr

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 05a3cbb and c351091.

📒 Files selected for processing (2)
  • apps/dashboard/app/auth/sign-in/oauth-signin.tsx (1 hunks)
  • apps/dashboard/app/auth/sign-up/oauth-signup.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/dashboard/app/auth/sign-in/oauth-signin.tsx
  • apps/dashboard/app/auth/sign-up/oauth-signup.tsx

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

vercel bot commented Oct 25, 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 28, 2024 7:57am

Copy link
Contributor

github-actions bot commented Oct 25, 2024

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

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 (4)
apps/dashboard/app/auth/sign-up/oauth-signup.tsx (2)

Line range hint 27-30: Enhance error handling with more specific error messages.

While the error handling covers the basics, it could be more informative and type-safe.

Consider this enhanced implementation:

-    } catch (cause) {
-      console.error(cause);
+    } catch (error: unknown) {
+      console.error('[OAuth Error]:', {
+        provider,
+        error,
+        timestamp: new Date().toISOString()
+      });
       setIsLoading(null);
-      toast.error("Something went wrong, please try again.");
+      toast.error(
+        error instanceof Error
+          ? `Authentication failed: ${error.message}`
+          : "Something went wrong with authentication, please try again."
+      );

Line range hint 34-48: Prevent potential race conditions and improve accessibility.

The current implementation could be susceptible to race conditions from rapid clicks, and the loading state could be more accessible.

Consider these improvements:

-      <OAuthButton onClick={() => oauthSignIn("oauth_github")}>
+      <OAuthButton
+        onClick={() => oauthSignIn("oauth_github")}
+        disabled={isLoading !== null}
+        aria-busy={isLoading === "oauth_github"}
+      >
         {isLoading === "oauth_github" ? (
-          <Loading className="w-6 h-6" />
+          <Loading className="w-6 h-6" aria-hidden="true" />
         ) : (
           <GitHub className="w-6 h-6" />
         )}
         GitHub
       </OAuthButton>
-      <OAuthButton onClick={() => oauthSignIn("oauth_google")}>
+      <OAuthButton
+        onClick={() => oauthSignIn("oauth_google")}
+        disabled={isLoading !== null}
+        aria-busy={isLoading === "oauth_google"}
+      >
apps/dashboard/app/auth/sign-in/oauth-signin.tsx (2)

Line range hint 19-33: Consider implementing navigation state management.

The current implementation might benefit from a more robust navigation state management approach. Consider using React's useEffect for cleanup:

 const oauthSignIn = async (provider: OAuthStrategy) => {
   if (!signInLoaded) {
     return null;
   }
   try {
     setIsLoading(provider);
     await signIn.authenticateWithRedirect({
       strategy: provider,
       redirectUrl: "/auth/sso-callback",
       redirectUrlComplete: "/apis",
     });
-    setIsLoading(null);
     setLastUsed(provider === "oauth_google" ? "google" : "github");
   } catch (err) {
     console.error(err);
     setIsLoading(null);
     toast.error((err as Error).message);
   }
 };
+
+ React.useEffect(() => {
+   return () => {
+     // Reset loading state when component unmounts (including navigation)
+     setIsLoading(null);
+   };
+ }, []);

28-28: Ensure consistent state management.

The setLastUsed call after setIsLoading(null) might be unnecessary if navigation occurs, as the component will unmount.

Consider moving the setLastUsed call before setIsLoading(null) to maintain a more logical state update sequence.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 15b6887 and 05a3cbb.

📒 Files selected for processing (2)
  • apps/dashboard/app/auth/sign-in/oauth-signin.tsx (1 hunks)
  • apps/dashboard/app/auth/sign-up/oauth-signup.tsx (1 hunks)
🔇 Additional comments (2)
apps/dashboard/app/auth/sign-up/oauth-signup.tsx (1)

Line range hint 1-48: Verify consistent implementation across sign-in and sign-up flows.

Let's ensure the proposed changes are consistently implemented across both OAuth components.

✅ Verification successful

Let me gather more information about the implementation details of both OAuth components.


Let me try a different approach to get the OAuth SignIn implementation:


Let me try one final search to get the complete implementation of the OAuth SignIn component:


Inconsistency found in redirect URLs between sign-in and sign-up flows

The verification revealed that while both OAuth components use the same /auth/sso-callback for redirectUrl, they have different redirectUrlComplete values:

  • Sign-up: redirects to /new
  • Sign-in: redirects to /apis

This difference appears intentional as it directs users to different pages based on their authentication flow.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent implementation across OAuth components
# and verify OAuthButton component properties

# Check OAuth components implementation
echo "Checking OAuth components implementation..."
rg -l "OAuthSign(In|Up)" apps/dashboard/app/auth/

# Verify OAuthButton component properties
echo "Checking OAuthButton component properties..."
ast-grep --pattern 'interface OAuthButtonProps {
  $$$
}'

Length of output: 517


Script:

#!/bin/bash
# Check implementation details of both OAuth components
echo "Checking OAuth SignIn implementation..."
rg -A 30 "export function OAuthSignIn" apps/dashboard/app/auth/sign-in/oauth-signin.tsx

echo "\nChecking OAuth SignUp implementation..."
rg -A 30 "export function OAuthSignUp" apps/dashboard/app/auth/sign-up/oauth-signup.tsx

# Check OAuthButton implementation
echo "\nChecking OAuthButton implementation..."
rg -A 10 "export function OAuthButton" apps/dashboard/app/auth/oauth-button.tsx

Length of output: 1461


Script:

#!/bin/bash
# Using ast-grep to find the OAuth components implementation
echo "Checking OAuth SignIn implementation..."
ast-grep --pattern 'export function OAuthSignIn() {
  $$$
}'

echo "Checking OAuthButton implementation..."
ast-grep --pattern 'export function OAuthButton($$$) {
  $$$
}'

# Also check the imports to ensure consistency
echo "Checking imports in OAuth SignIn..."
rg "^import.*from" apps/dashboard/app/auth/sign-in/oauth-signin.tsx

echo "Checking imports in OAuth SignUp..."
rg "^import.*from" apps/dashboard/app/auth/sign-up/oauth-signup.tsx

Length of output: 1331


Script:

#!/bin/bash
# Search for the complete OAuth SignIn implementation with more context
echo "Checking complete OAuth SignIn implementation..."
rg -U "export function OAuthSignIn.*?}" apps/dashboard/app/auth/sign-in/oauth-signin.tsx -A 50 -m 1

# Also check the redirectUrl and redirectUrlComplete values
echo "Checking redirect URLs usage..."
rg "redirectUrl.*|redirectUrlComplete.*" apps/dashboard/app/auth/

Length of output: 706

apps/dashboard/app/auth/sign-in/oauth-signin.tsx (1)

27-27: Verify the timing of loading state reset.

While setting isLoading to null after redirect initiation addresses the back navigation issue, it might cause the loading spinner to disappear prematurely during a successful authentication flow.

Consider these alternative approaches:

  1. Use beforeunload event listener to reset state on navigation
  2. Implement a cleanup function in a useEffect hook

@Srayash Srayash changed the title Bug Fix: OAuth Button Loader State Not Reset on Browser Back Navigation. fix: OAuth Button Loader State Not Reset on Browser Back Navigation. Oct 25, 2024
@unkeyed unkeyed deleted a comment from Srayash Oct 26, 2024
@Srayash
Copy link
Contributor Author

Srayash commented Oct 28, 2024

hey @chronark kindly review and give feedback or merge.
thanks!

@chronark chronark merged commit 985a412 into unkeyed:main Oct 28, 2024
5 of 9 checks passed
Copy link

oss-gg bot commented Oct 28, 2024

Awarding Srayash: 50 points 🕹️ Well done! Check out your new contribution on oss.gg/Srayash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

OAuth Button Loader State Not Reset on Browser Back Navigation
3 participants