supabase-community / auth-ui

Pre-built Auth UI for React
https://supabase.com/docs/guides/auth/auth-helpers/auth-ui
MIT License
488 stars 121 forks source link

Added onViewChanged to React Auth UI so that view can be externally synchronized #260

Open davidmc971 opened 6 months ago

davidmc971 commented 6 months ago

What kind of change does this PR introduce?

This introduces a feature where you can pass a callback onViewChanged to the Auth component for React. This callback gets executed, whenever the view of the Auth UI changes so that you can externally synchronize with it.

My specific use-case of it was that I wanted to synchronize the redirectUrl with whatever view a user selected. For example on sign up I want to redirect to [main app URL]/onboarding while on the forgotten password page I want to redirect to [main app URL]/reset-password.

This could also potentially help with #236 and #223

Also remember that the redirectUrl needs to match the redirect URL settings on Supabase.

What is the current behavior?

When a view is selected, that state is isolated to the Auth UI component. You can pass the initial view, but cannot listen to changes.

What is the new behavior?

See feature description above; onViewChanged gets called by Auth UI component whenever the view changes.

Additional context

Example of how I use this new feature:

  const [view, setView] = useState<ViewType>("sign_in");
  const [redirectTo, setRedirectTo] = useState<string | undefined>();

  useEffect(() => {
    const currentUrl = new URL(window.location.href);
    switch (view) {
      case "sign_in":
      case "sign_up":
        setRedirectTo(currentUrl.origin + "/onboarding");
        break;
      case "forgotten_password":
        setRedirectTo(currentUrl.origin + "/reset-password");
        break;
      default:
        setRedirectTo(undefined);
        break;
    }
  }, [view]);
          <Auth
            supabaseClient={supabase}
            view={view}
            onViewChange={(view) => {
              setView(view);
            }}
            redirectTo={redirectTo}
          />
jona-sc commented 2 months ago

Nice change - how can we get it merged?