From fcc56197a4ec5ba4edbeaa0a163729d5216b5efc Mon Sep 17 00:00:00 2001 From: Ayush Rodrigues Date: Mon, 27 Apr 2026 14:49:38 +0100 Subject: [PATCH] Persist last-active org in localStorage to prevent org reset on stale sessions When GET /organization fails transiently (e.g. after session refresh overnight), the fallback now restores the user's last-active org from localStorage instead of picking an arbitrary org from the list. Made-with: Cursor --- vite/src/hooks/common/useOrg.tsx | 41 +++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/vite/src/hooks/common/useOrg.tsx b/vite/src/hooks/common/useOrg.tsx index eca60e5f4..26c9e6c97 100644 --- a/vite/src/hooks/common/useOrg.tsx +++ b/vite/src/hooks/common/useOrg.tsx @@ -5,11 +5,21 @@ import { authClient, useListOrganizations } from "@/lib/auth-client"; import { useAxiosInstance } from "@/services/useAxiosInstance"; import { useEnv } from "@/utils/envUtils"; -let lastSwitchedOrgId: string | null = null; +const LAST_ORG_KEY = "autumn_last_active_org_id"; + export const setLastSwitchedOrgId = (id: string) => { - lastSwitchedOrgId = id; + try { + localStorage.setItem(LAST_ORG_KEY, id); + } catch {} +}; + +export const getLastSwitchedOrgId = (): string | null => { + try { + return localStorage.getItem(LAST_ORG_KEY); + } catch { + return null; + } }; -export const getLastSwitchedOrgId = () => lastSwitchedOrgId; export const useOrg = (params?: { env?: AppEnv }) => { const currentEnv = useEnv(); @@ -38,18 +48,31 @@ export const useOrg = (params?: { env?: AppEnv }) => { staleTime: 30_000, }); + useEffect(() => { + if (org?.id) { + setLastSwitchedOrgId(org.id); + } + }, [org?.id]); + useEffect(() => { const handleNoActiveOrg = async () => { - if (orgList && orgList.length > 0) { - await authClient.organization.setActive({ - organizationId: orgList[0].id, - }); - window.location.reload(); - } else { + if (!orgList || orgList.length === 0) { console.log("No org to set active, signing out"); await authClient.signOut(); window.location.href = "/sign-in"; + return; } + + const lastOrgId = getLastSwitchedOrgId(); + const preferredOrg = lastOrgId + ? orgList.find((o) => o.id === lastOrgId) + : null; + const targetOrgId = preferredOrg?.id ?? orgList[0].id; + + await authClient.organization.setActive({ + organizationId: targetOrgId, + }); + window.location.reload(); }; if (!org && !isLoading) {