Files
home/Projects/kompose/news/apps/web/src/hooks/useSession.ts

38 lines
930 B
TypeScript
Raw Normal View History

2025-10-10 16:43:21 +02:00
import { trpc } from "@/trpc";
import Cookies from "js-cookie";
import { useCallback, useEffect, useMemo } from "react";
import { useNavigate } from "react-router";
import { useLocalStorage } from "usehooks-ts";
2025-10-08 10:35:48 +02:00
export function useSession() {
2025-10-10 16:43:21 +02:00
const [orgId, setOrgId, removeOrgId] = useLocalStorage("orgId", "");
const user = trpc.user.me.useQuery();
2025-10-08 10:35:48 +02:00
2025-10-10 16:43:21 +02:00
const organization = useMemo(() => {
return (
user.data?.UserOrganizations.find((uo) => uo.organizationId === orgId)
?.Organization || null
);
}, [user.data, orgId]);
2025-10-08 10:35:48 +02:00
2025-10-10 16:43:21 +02:00
const navigate = useNavigate();
2025-10-08 10:35:48 +02:00
2025-10-10 16:43:21 +02:00
useEffect(() => {
if (!user.isLoading && !user.data) {
navigate("/");
}
2025-10-08 10:35:48 +02:00
2025-10-10 16:43:21 +02:00
if (!orgId) {
navigate("/");
}
}, [orgId, user.data, navigate, user.isLoading]);
2025-10-08 10:35:48 +02:00
2025-10-10 16:43:21 +02:00
const logout = useCallback(() => {
removeOrgId();
Cookies.remove("token");
window.location.href = "/";
}, [removeOrgId]);
2025-10-08 10:35:48 +02:00
2025-10-10 16:43:21 +02:00
return { orgId, setOrgId, user, organization, logout };
2025-10-08 10:35:48 +02:00
}