@@ -23,6 +23,10 @@ import HTTP_CODES_ENUM from "../api/types/http-codes";
23
23
24
24
function AuthProvider ( props : PropsWithChildren < { } > ) {
25
25
const AUTH_TOKEN_KEY = "auth-token-data" ;
26
+ const [ tabId ] = useState ( ( ) => Math . random ( ) . toString ( 36 ) . slice ( 2 ) ) ;
27
+ const [ broadcastChannel ] = useState (
28
+ ( ) => new BroadcastChannel ( AUTH_TOKEN_KEY )
29
+ ) ;
26
30
const [ isLoaded , setIsLoaded ] = useState ( false ) ;
27
31
const [ user , setUser ] = useState < User | null > ( null ) ;
28
32
const tokensInfoRef = useRef < Tokens > ( {
@@ -43,6 +47,10 @@ function AuthProvider(props: PropsWithChildren<{}>) {
43
47
const setTokensInfo = useCallback (
44
48
( tokensInfo : TokensInfo ) => {
45
49
setTokensInfoRef ( tokensInfo ) ;
50
+ broadcastChannel . postMessage ( {
51
+ tabId,
52
+ tokens : tokensInfo ,
53
+ } ) ;
46
54
47
55
if ( tokensInfo ) {
48
56
Cookies . set ( AUTH_TOKEN_KEY , JSON . stringify ( tokensInfo ) ) ;
@@ -51,7 +59,7 @@ function AuthProvider(props: PropsWithChildren<{}>) {
51
59
setUser ( null ) ;
52
60
}
53
61
} ,
54
- [ setTokensInfoRef ]
62
+ [ setTokensInfoRef , broadcastChannel , tabId ]
55
63
) ;
56
64
57
65
const logOut = useCallback ( async ( ) => {
@@ -112,6 +120,26 @@ function AuthProvider(props: PropsWithChildren<{}>) {
112
120
loadData ( ) ;
113
121
} , [ loadData ] ) ;
114
122
123
+ useEffect ( ( ) => {
124
+ const onMessage = (
125
+ event : MessageEvent < {
126
+ tabId : string ;
127
+ tokens : TokensInfo ;
128
+ } >
129
+ ) => {
130
+ if ( event . data . tabId === tabId ) return ;
131
+
132
+ if ( ! event . data . tokens ) setUser ( null ) ;
133
+ setTokensInfoRef ( event . data . tokens ) ;
134
+ } ;
135
+
136
+ broadcastChannel . addEventListener ( "message" , onMessage ) ;
137
+
138
+ return ( ) => {
139
+ broadcastChannel . removeEventListener ( "message" , onMessage ) ;
140
+ } ;
141
+ } , [ broadcastChannel , setTokensInfoRef , tabId ] ) ;
142
+
115
143
const contextValue = useMemo (
116
144
( ) => ( {
117
145
isLoaded,
0 commit comments