|
| 1 | +import { |
| 2 | + Do, |
| 3 | + EnvironmentUtils, |
| 4 | + ResultRecord, |
| 5 | +} from "andculturecode-javascript-core"; |
| 6 | +import { useCallback, useEffect, useState } from "react"; |
| 7 | +import { UseQueryOptions } from "../interfaces/use-query-options"; |
| 8 | +import { ListService } from "../types/list-service-type"; |
| 9 | +import { NestedListService } from "../types/nested-list-service-type"; |
| 10 | + |
| 11 | +export function useQuery<TRecord, TQueryParams, TPathParams = undefined>( |
| 12 | + options: UseQueryOptions<TRecord, TQueryParams, TPathParams> |
| 13 | +) { |
| 14 | + const { |
| 15 | + initialPathParams, |
| 16 | + initialQuery, |
| 17 | + onError, |
| 18 | + onSuccess, |
| 19 | + serviceHook, |
| 20 | + } = options; |
| 21 | + |
| 22 | + const { list: listApi } = serviceHook(); |
| 23 | + |
| 24 | + const handleSuccess = useCallback( |
| 25 | + (records: Array<TRecord>) => { |
| 26 | + if (onSuccess != null) { |
| 27 | + onSuccess(records); |
| 28 | + return; |
| 29 | + } |
| 30 | + }, |
| 31 | + [onSuccess] |
| 32 | + ); |
| 33 | + |
| 34 | + const handleError = useCallback( |
| 35 | + (result?: ResultRecord<TRecord>, error?: any) => { |
| 36 | + if (onError != null) { |
| 37 | + onError(result, error); |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + EnvironmentUtils.runIfDevelopment(() => { |
| 42 | + console.error("No error handler defined."); |
| 43 | + console.error(result, error); |
| 44 | + }); |
| 45 | + }, |
| 46 | + [onError] |
| 47 | + ); |
| 48 | + |
| 49 | + const [loading, setLoading] = useState(false); |
| 50 | + const [query, setQuery] = useState(initialQuery); |
| 51 | + const [pathParams, setPathParams] = useState(initialPathParams); |
| 52 | + const [values, setValues] = useState<Array<TRecord>>([]); |
| 53 | + |
| 54 | + useEffect(() => { |
| 55 | + Do.try(async () => { |
| 56 | + // if regular list, not nested list |
| 57 | + if (pathParams == null) { |
| 58 | + const api = listApi as ListService<TRecord, TQueryParams>; |
| 59 | + const result = await api(query); |
| 60 | + setValues(result.resultObjects!); |
| 61 | + handleSuccess(result.resultObjects!); |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + // otherwise, nested list |
| 66 | + const api = listApi as NestedListService< |
| 67 | + TRecord, |
| 68 | + TPathParams, |
| 69 | + TQueryParams |
| 70 | + >; |
| 71 | + const result = await api(pathParams, query); |
| 72 | + setValues(result.resultObjects!); |
| 73 | + handleSuccess(result.resultObjects!); |
| 74 | + }) |
| 75 | + .catch(handleError) |
| 76 | + .finally(() => setLoading(false)); |
| 77 | + }); |
| 78 | + |
| 79 | + return { |
| 80 | + loading, |
| 81 | + query, |
| 82 | + setQuery, |
| 83 | + pathParams, |
| 84 | + setPathParams, |
| 85 | + values, |
| 86 | + setValues, |
| 87 | + }; |
| 88 | +} |
0 commit comments