Files
prowler/ui/components/users/forms/switch-tenant-form.tsx
2026-07-23 13:26:54 +02:00

78 lines
2.0 KiB
TypeScript

"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<SetStateAction<boolean>>;
}) => {
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 (
<form action={formAction}>
<input type="hidden" name="tenantId" value={tenantId} />
<FormButtons
setIsOpen={setIsOpen}
submitText="Confirm"
loadingText="Switching"
rightIcon={null}
/>
</form>
);
};