diff --git a/src/lib/category/index.ts b/src/lib/category/index.ts new file mode 100644 index 00000000..f2437b73 --- /dev/null +++ b/src/lib/category/index.ts @@ -0,0 +1 @@ +export { useDefaultCategoryComboQuery } from './useDefaultCategoryComboQuery' diff --git a/src/lib/category/useDefaultCategoryComboQuery.ts b/src/lib/category/useDefaultCategoryComboQuery.ts new file mode 100644 index 00000000..ef06bc37 --- /dev/null +++ b/src/lib/category/useDefaultCategoryComboQuery.ts @@ -0,0 +1,46 @@ +import { useDataQuery } from '@dhis2/app-runtime' +import { useMemo } from 'react' +import { CategoryCombo } from '../../types/generated' + +type DefaultCategoryComboQueryResult = { + categoryCombos: { + categoryCombos: CategoryCombo[] + } +} + +const DEFAULT_CATEGORY_OPTION_QUERY = { + categoryCombos: { + resource: 'categoryCombos', + params: (variables: Record) => { + const fields = ['id'] + if (variables.fields) { + fields.push(...variables.fields) + } + + return { + fields, + paging: false, + filter: ['isDefault:eq:true'], + } + }, + }, +} + +export function useDefaultCategoryComboQuery({ + fields, +}: { fields?: string[] } = {}) { + const variables = { fields } + // The gist doesn't include the `isDefault` value, need to use `useDataQuery` + const queryResult = useDataQuery( + DEFAULT_CATEGORY_OPTION_QUERY, + { variables } + ) + + return useMemo( + () => ({ + ...queryResult, + data: queryResult.data?.categoryCombos.categoryCombos[0], + }), + [queryResult] + ) +} diff --git a/src/lib/index.ts b/src/lib/index.ts index fe63ee89..c0b484aa 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -1,3 +1,4 @@ +export * from './category' export * from './constants' export * from './debounce' export * from './models'