1
- import { createContext , type FC , type PropsWithChildren } from "react" ;
1
+ import {
2
+ createContext ,
3
+ type FC ,
4
+ type PropsWithChildren ,
5
+ useState ,
6
+ } from "react" ;
2
7
import { useQuery } from "react-query" ;
3
8
import { appearance } from "api/queries/appearance" ;
4
9
import { entitlements } from "api/queries/entitlements" ;
@@ -9,9 +14,13 @@ import type {
9
14
Experiments ,
10
15
} from "api/typesGenerated" ;
11
16
import { Loader } from "components/Loader/Loader" ;
17
+ import { useAuthenticated } from "contexts/auth/RequireAuth" ;
18
+ import { useEffectEvent } from "hooks/hookPolyfills" ;
12
19
import { useEmbeddedMetadata } from "hooks/useEmbeddedMetadata" ;
13
20
14
21
export interface DashboardValue {
22
+ organizationId :string ;
23
+ setOrganizationId :( id :string ) => void ;
15
24
entitlements :Entitlements ;
16
25
experiments :Experiments ;
17
26
appearance :AppearanceConfig ;
@@ -23,20 +32,40 @@ export const DashboardContext = createContext<DashboardValue | undefined>(
23
32
24
33
export const DashboardProvider :FC < PropsWithChildren > = ( { children} ) => {
25
34
const { metadata} = useEmbeddedMetadata ( ) ;
35
+ const { user, organizationIds} = useAuthenticated ( ) ;
26
36
const entitlementsQuery = useQuery ( entitlements ( metadata . entitlements ) ) ;
27
37
const experimentsQuery = useQuery ( experiments ( metadata . experiments ) ) ;
28
38
const appearanceQuery = useQuery ( appearance ( metadata . appearance ) ) ;
29
39
30
40
const isLoading =
31
41
! entitlementsQuery . data || ! appearanceQuery . data || ! experimentsQuery . data ;
32
42
43
+ const lastUsedOrganizationId = localStorage . getItem (
44
+ `user:${ user . id } .lastUsedOrganizationId` ,
45
+ ) ;
46
+ const [ activeOrganizationId , setActiveOrganizationId ] = useState ( ( ) =>
47
+ lastUsedOrganizationId && organizationIds . includes ( lastUsedOrganizationId )
48
+ ?lastUsedOrganizationId
49
+ :organizationIds [ 0 ] ,
50
+ ) ;
51
+
52
+ const setOrganizationId = useEffectEvent ( ( id :string ) => {
53
+ if ( ! organizationIds . includes ( id ) ) {
54
+ throw new ReferenceError ( "Invalid organization ID" ) ;
55
+ }
56
+ localStorage . setItem ( `user:${ user . id } .lastUsedOrganizationId` , id ) ;
57
+ setActiveOrganizationId ( id ) ;
58
+ } ) ;
59
+
33
60
if ( isLoading ) {
34
61
return < Loader fullscreen /> ;
35
62
}
36
63
37
64
return (
38
65
< DashboardContext . Provider
39
66
value = { {
67
+ organizationId :activeOrganizationId ,
68
+ setOrganizationId :setOrganizationId ,
40
69
entitlements :entitlementsQuery . data ,
41
70
experiments :experimentsQuery . data ,
42
71
appearance :appearanceQuery . data ,