|
| 1 | +import { |
| 2 | + useState, useEffect, DependencyList, |
| 3 | +} from 'react'; |
| 4 | + |
| 5 | +import { REQUEST_POLLING_CANCELLED, NotificationMapper, RequestApi } from '@fpsak-frontend/rest-api-new'; |
| 6 | + |
| 7 | +import useRestApiErrorDispatcher from '../error/useRestApiErrorDispatcher'; |
| 8 | +import RestApiState from '../RestApiState'; |
| 9 | + |
| 10 | +interface RestApiData<T> { |
| 11 | + state: RestApiState; |
| 12 | + error?: Error; |
| 13 | + data?: T; |
| 14 | +} |
| 15 | + |
| 16 | +interface Options { |
| 17 | + updateTriggers?: DependencyList; |
| 18 | + keepData?: boolean; |
| 19 | + suspendRequest?: boolean; |
| 20 | +} |
| 21 | + |
| 22 | +const defaultOptions = { |
| 23 | + updateTriggers: [], |
| 24 | + keepData: false, |
| 25 | + suspendRequest: false, |
| 26 | +}; |
| 27 | + |
| 28 | +/** |
| 29 | + * Hook som utfører et restkall ved mount. En kan i tillegg legge ved en dependencies-liste som kan trigge ny henting når data |
| 30 | + * blir oppdatert. Hook returnerer rest-kallets status/resultat/feil |
| 31 | + */ |
| 32 | +const getUseRestApi = (requestApi: RequestApi) => function useRestApi<T>(key: string, params: any = {}, options: Options = defaultOptions):RestApiData<T> { |
| 33 | + const [data, setData] = useState({ |
| 34 | + state: RestApiState.NOT_STARTED, |
| 35 | + error: undefined, |
| 36 | + data: undefined, |
| 37 | + }); |
| 38 | + |
| 39 | + const { addErrorMessage } = useRestApiErrorDispatcher(); |
| 40 | + const notif = new NotificationMapper(); |
| 41 | + notif.addRequestErrorEventHandlers((errorData, type) => { |
| 42 | + addErrorMessage({ ...errorData, type }); |
| 43 | + }); |
| 44 | + |
| 45 | + useEffect(() => { |
| 46 | + if (requestApi.hasPath(key) && !options.suspendRequest) { |
| 47 | + setData((oldState) => ({ |
| 48 | + state: RestApiState.LOADING, |
| 49 | + error: undefined, |
| 50 | + data: options.keepData ? oldState.data : undefined, |
| 51 | + })); |
| 52 | + |
| 53 | + requestApi.startRequest(key, params, notif) |
| 54 | + .then((dataRes) => { |
| 55 | + if (dataRes.payload !== REQUEST_POLLING_CANCELLED) { |
| 56 | + setData({ |
| 57 | + state: RestApiState.SUCCESS, |
| 58 | + data: dataRes.payload, |
| 59 | + error: undefined, |
| 60 | + }); |
| 61 | + } |
| 62 | + }) |
| 63 | + .catch((error) => { |
| 64 | + setData({ |
| 65 | + state: RestApiState.ERROR, |
| 66 | + data: undefined, |
| 67 | + error, |
| 68 | + }); |
| 69 | + }); |
| 70 | + } else { |
| 71 | + setData({ |
| 72 | + state: RestApiState.NOT_STARTED, |
| 73 | + error: undefined, |
| 74 | + data: undefined, |
| 75 | + }); |
| 76 | + } |
| 77 | + }, options.updateTriggers); |
| 78 | + |
| 79 | + return data; |
| 80 | +}; |
| 81 | + |
| 82 | +export default getUseRestApi; |
0 commit comments