Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

1.3 KB
Raw Blame
import { useEffect, useState } from "react";
import { ensurePortalSessionClient } from "@editor/portal/auth/sessionClient";
import { usePortalSaasSession } from "@editor/portal/hooks/usePortalSaasSession";

/**
 * Current browser SaaS identity, independent of the local server login or connection owner.
 * Null means no email is available. Tracks sign-in and sign-out without depending on LinkContext.
 */
export function useLinkedAccountEmail(): string | null {
  const { revision } = usePortalSaasSession();
  const [email, setEmail] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    let sessionChanged = false;
    const supabase = ensurePortalSessionClient();
    if (!supabase) {
      setEmail(null);
      return;
    }
    const {
      data: { subscription },
    } = supabase.auth.onAuthStateChange((_event, session) => {
      sessionChanged = true;
      if (!cancelled) setEmail(session?.user?.email ?? null);
    });
    void supabase.auth
      .getSession()
      .then(({ data }) => {
        if (!cancelled && !sessionChanged)
          setEmail(data.session?.user?.email ?? null);
      })
      .catch(() => {
        if (!cancelled && !sessionChanged) setEmail(null);
      });
    return () => {
      cancelled = true;
      subscription.unsubscribe();
    };
  }, [revision]);

  return email;
}