| 1 |
import { useState, useEffect } from 'react'; |
| 2 |
import LoadState, { LoadStateType } from '../../../shared/enums/loadState'; |
| 3 |
import { ProxyMessages } from '../../../iframe/integratedMessages'; |
| 4 |
import { usePostAsyncBackgroundMessage } from '../../../iframe/useBackgroundApp'; |
| 5 |
import { IForm } from '../../../shared/types'; |
| 6 |
|
| 7 |
interface FormOption { |
| 8 |
label: string; |
| 9 |
value: string; |
| 10 |
} |
| 11 |
|
| 12 |
export default function useForms() { |
| 13 |
const proxy = usePostAsyncBackgroundMessage(); |
| 14 |
const [loadState, setLoadState] = useState<LoadStateType>( |
| 15 |
LoadState.NotLoaded |
| 16 |
); |
| 17 |
const [hasError, setError] = useState(null); |
| 18 |
const [forms, setForms] = useState<FormOption[]>([]); |
| 19 |
|
| 20 |
useEffect(() => { |
| 21 |
if (loadState === LoadState.NotLoaded) { |
| 22 |
proxy({ |
| 23 |
key: ProxyMessages.FetchForms, |
| 24 |
payload: { |
| 25 |
search: '', |
| 26 |
}, |
| 27 |
}) |
| 28 |
.then(data => { |
| 29 |
setForms( |
| 30 |
data.map((form: IForm) => ({ |
| 31 |
label: form.name, |
| 32 |
value: form.guid, |
| 33 |
})) |
| 34 |
); |
| 35 |
setLoadState(LoadState.Loaded); |
| 36 |
}) |
| 37 |
.catch(error => { |
| 38 |
setError(error); |
| 39 |
setLoadState(LoadState.Failed); |
| 40 |
}); |
| 41 |
} |
| 42 |
}, [loadState]); |
| 43 |
|
| 44 |
return { forms, loading: loadState === LoadState.Loading, hasError }; |
| 45 |
} |
| 46 |
|