1
1
import { useAtom } from 'jotai'
2
- import { FC , useEffect } from 'react'
2
+ import { FC , useRef } from 'react'
3
3
4
4
import { authAtom , fromCredentials } from 'store/auth'
5
5
import { FETCHER_CONFIG } from 'utils/fetcher'
@@ -10,8 +10,14 @@ import { AppToaster } from './Toaster'
10
10
11
11
export const Effects : FC = ( ) => {
12
12
const [ auth , setAuth ] = useAtom ( authAtom )
13
+ const lastAuth = useRef < typeof auth | null > ( null )
14
+
15
+ // here we are simulating a synchronous version of useEffect(() => {}, [auth])
16
+ // in order to set the FETCHER_CONFIG.apiToken before any useSWR() call,
17
+ // because useSWR() seems to send request synchronously, and useEffect() is too late
18
+ if ( lastAuth . current !== auth ) {
19
+ lastAuth . current = auth
13
20
14
- useEffect ( ( ) => {
15
21
const { token, validBefore, refreshToken, refreshTokenValidBefore } = auth
16
22
17
23
const endTime = + new Date ( validBefore || 0 ) || 0
@@ -32,7 +38,7 @@ export const Effects: FC = () => {
32
38
}
33
39
34
40
if ( ! refreshToken ) {
35
- // seems that user was logging in in previous version of the app
41
+ // the refresh token is somehow missing, no way to update the token
36
42
shouldLogout = true
37
43
}
38
44
}
@@ -66,6 +72,9 @@ export const Effects: FC = () => {
66
72
}
67
73
68
74
if ( shouldLogout ) {
75
+ // FIXME: setting the state synchronously may cause problems (not really sure), so we add a small delay for a temporary hack
76
+ await new Promise ( ( resolve ) => setTimeout ( resolve , 50 ) )
77
+
69
78
setAuth ( { } )
70
79
AppToaster . show ( {
71
80
intent : 'warning' ,
@@ -84,7 +93,7 @@ export const Effects: FC = () => {
84
93
}
85
94
86
95
FETCHER_CONFIG . apiToken = currentFn
87
- } , [ auth ] )
96
+ }
88
97
89
98
return null
90
99
}
0 commit comments