33import { useState , useEffect } from "react" ;
44import { useAuth } from "@clerk/nextjs" ;
55import { useQuery } from "@tanstack/react-query" ;
6+ import { useRouter , usePathname } from "next/navigation" ;
67import { useActiveAccount } from "@/components/providers/active-account-provider" ;
78import { userTeamsOptions } from "@/lib/queries/team" ;
89
10+ const RESTRICTED_DASHBOARD_PATTERNS = [
11+ / ^ \/ d a s h b o a r d \/ e v e n t \/ [ ^ / ] + / ,
12+ / ^ \/ d a s h b o a r d \/ c o m m u n i t y \/ [ ^ / ] + / ,
13+ ] ;
14+
15+ function isRestrictedPage ( pathname : string ) : boolean {
16+ return RESTRICTED_DASHBOARD_PATTERNS . some ( ( pattern ) =>
17+ pattern . test ( pathname ) ,
18+ ) ;
19+ }
20+
921export function useAccountSwitcher ( userId : string ) {
1022 const { getToken } = useAuth ( ) ;
1123 const { activeAccount, switchAccount } = useActiveAccount ( ) ;
1224 const [ isCreateTeamOpen , setIsCreateTeamOpen ] = useState ( false ) ;
25+ const router = useRouter ( ) ;
26+ const pathname = usePathname ( ) ;
1327
1428 const { data : teams = [ ] , isFetched } = useQuery (
1529 userTeamsOptions ( getToken , userId ) ,
1630 ) ;
1731 const isPersonalActive = ! activeAccount || activeAccount . type === "personal" ;
1832
1933 useEffect ( ( ) => {
20- if ( ! isFetched || activeAccount ?. type !== "team" ) return ;
34+ if ( ! userId ) return ;
35+
36+ if ( ! activeAccount ) {
37+ switchAccount ( { type : "personal" , id : userId } ) ;
38+ return ;
39+ }
40+
41+ if ( ! isFetched || activeAccount . type !== "team" ) return ;
42+
2143 const teamExists = teams . some ( ( t ) => t . teamId === activeAccount . id ) ;
2244 if ( ! teamExists ) {
2345 switchAccount ( { type : "personal" , id : userId } ) ;
@@ -29,13 +51,19 @@ export function useAccountSwitcher(userId: string) {
2951 type : "personal" ,
3052 id : userId ,
3153 } ) ;
54+ if ( isRestrictedPage ( pathname ) ) {
55+ router . push ( "/dashboard" ) ;
56+ }
3257 } ;
3358
3459 const handleSwitchToTeam = ( teamId : string ) => {
3560 switchAccount ( {
3661 type : "team" ,
3762 id : teamId ,
3863 } ) ;
64+ if ( isRestrictedPage ( pathname ) ) {
65+ router . push ( "/dashboard" ) ;
66+ }
3967 } ;
4068
4169 return {
0 commit comments