use-settings.ts1.5 KBView on GitHub
import { useScopedOptionalInput } from '@/modules/administeredUser';
import { useSession } from '@/modules/auth/utils/auth-client';
import { useTRPC } from '@/providers/query-provider';
import { useQuery } from '@tanstack/react-query';

/**
 * The signed-in user's own settings.
 *
 * This is deliberately NOT scoped to the administered teammate. It backs the
 * global chrome: theme, locale, inboxes, composer, calendar, the user menu. If
 * it followed the picker, choosing a teammate would repaint the admin's own app
 * in that teammate's settings. Only the settings PAGES read the administered
 * user, through `useAdministeredSettings`.
 */
export function useSettings() {
  const { data: session } = useSession();
  const trpc = useTRPC();

  const settingsQuery = useQuery(
    trpc.settings.get.queryOptions(void 0, {
      enabled: !!session?.user.id,
      staleTime: Infinity,
    }),
  );

  return settingsQuery;
}

/**
 * Settings for whoever is being administered: the teammate an org admin picked,
 * or the signed-in user otherwise.
 *
 * When administering yourself the input is `undefined`, so this is the same
 * query as `useSettings` down to the cache key, and costs nothing extra.
 */
export function useAdministeredSettings() {
  const { data: session } = useSession();
  const trpc = useTRPC();
  const scope = useScopedOptionalInput();

  return useQuery(
    trpc.settings.get.queryOptions(scope, {
      enabled: !!session?.user.id,
      staleTime: Infinity,
    }),
  );
}