| 1 |
import { useEffect, useState } from 'react'; |
| 2 |
import { usePostAsyncBackgroundMessage } from '../../../iframe/useBackgroundApp'; |
| 3 |
import LoadState, { LoadStateType } from '../../enums/loadState'; |
| 4 |
import { ProxyMessages } from '../../../iframe/integratedMessages'; |
| 5 |
|
| 6 |
let user: any = null; |
| 7 |
|
| 8 |
export default function useCurrentUserFetch() { |
| 9 |
const proxy = usePostAsyncBackgroundMessage(); |
| 10 |
const [loadState, setLoadState] = useState<LoadStateType>( |
| 11 |
LoadState.NotLoaded |
| 12 |
); |
| 13 |
const [error, setError] = useState<null | Error>(null); |
| 14 |
|
| 15 |
const createUser = () => { |
| 16 |
if (!user) { |
| 17 |
setLoadState(LoadState.NotLoaded); |
| 18 |
} |
| 19 |
}; |
| 20 |
|
| 21 |
const reload = () => { |
| 22 |
user = null; |
| 23 |
setLoadState(LoadState.NotLoaded); |
| 24 |
setError(null); |
| 25 |
}; |
| 26 |
|
| 27 |
useEffect(() => { |
| 28 |
if (loadState === LoadState.NotLoaded && !user) { |
| 29 |
setLoadState(LoadState.Loading); |
| 30 |
proxy({ |
| 31 |
key: ProxyMessages.FetchOrCreateMeetingUser, |
| 32 |
}) |
| 33 |
.then(data => { |
| 34 |
user = data; |
| 35 |
setLoadState(LoadState.Idle); |
| 36 |
}) |
| 37 |
.catch(err => { |
| 38 |
setError(err); |
| 39 |
setLoadState(LoadState.Failed); |
| 40 |
}); |
| 41 |
} |
| 42 |
}, [loadState]); |
| 43 |
|
| 44 |
return { user, loadUserState: loadState, error, createUser, reload }; |
| 45 |
} |
| 46 |
|