useAccount

tcmts.atproto.useAccount · #thrpejvn · function · runs in the browser

uses window

Who's signed in on this browser (undefined if no one), kept up to date: coming back from the sign-in page, it finishes signing in (#srwmtcby); error says what went wrong if that failed. Use it once in a page that every sign-in comes back to (the app's home page), and anywhere else to know who's signed in.

import { ACCOUNT_EVENT, finishSignIn, keptAccount } from "#codebase/tcmts/atproto";
import type { Account } from "#codebase/tcmts/atproto";
import { useEffect, useState } from "react";

export function useAccount(): { account: Account | undefined; error?: string } {
  const [state, setState] = useState<{ account: Account | undefined; error?: string }>({
    account: undefined,
  });
  useEffect(() => {
    const now = () => {
      const kept = keptAccount();
      setState({
        account: kept
          ? { did: kept.did, ...(kept.handle ? { handle: kept.handle } : {}) }
          : undefined,
      });
    };
    window.addEventListener(ACCOUNT_EVENT, now);
    finishSignIn().then(
      () => now(),
      (e: unknown) => setState({ account: keptAccount(), error: (e as Error).message }),
    );
    return () => window.removeEventListener(ACCOUNT_EVENT, now);
  }, []);
  return state;
}

uses

used by