"use client"; import { useSession } from "next-auth/react"; import { Dispatch, SetStateAction, useActionState, useEffect } from "react"; import { switchTenant } from "@/actions/users/tenants"; import { useToast } from "@/components/shadcn"; import { FormButtons } from "@/components/shadcn/form"; import { reloadPage } from "@/lib/navigation"; export const SwitchTenantForm = ({ tenantId, setIsOpen, }: { tenantId: string; setIsOpen: Dispatch>; }) => { const [state, formAction] = useActionState(switchTenant, null); const { update } = useSession(); const { toast } = useToast(); useEffect(() => { if (!state) return; const handleSwitch = async () => { if ("success" in state) { try { const updatedSession = await update({ accessToken: state.accessToken, refreshToken: state.refreshToken, }); if ( !updatedSession || ("error" in updatedSession && updatedSession.error) ) { throw new Error("Session update failed"); } toast({ title: "Organization switched", description: "The page will reload to apply the change.", }); reloadPage(); } catch { toast({ variant: "destructive", title: "Oops! Something went wrong", description: "Unable to switch organization. Please try again.", }); setIsOpen(false); } } else { toast({ variant: "destructive", title: "Oops! Something went wrong", description: state.error, }); setIsOpen(false); } }; handleSwitch(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [state]); return (
); };