Skip to content

Commit

Permalink
(feat) Fetch all concept references of the the form with SWR Infinite (
Browse files Browse the repository at this point in the history
…openmrs#241)

* Fetching all concepts references with useSWRInfinite

* Fixed failing tests
  • Loading branch information
vasharma05 authored and usamaidrsk committed Apr 29, 2024
1 parent f77fc72 commit 960da66
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 8 deletions.
50 changes: 43 additions & 7 deletions src/hooks/useConcepts.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,50 @@
import useSWRImmutable from 'swr/immutable';
import { openmrsFetch, OpenmrsResource, restBaseUrl } from '@openmrs/esm-framework';
import useSWRInfinite from 'swr/infinite';
import { FetchResponse, openmrsFetch, OpenmrsResource, restBaseUrl } from '@openmrs/esm-framework';
import { useMemo } from 'react';

const conceptRepresentation =
'custom:(uuid,display,conceptClass:(uuid,display),answers:(uuid,display),conceptMappings:(conceptReferenceTerm:(conceptSource:(name),code)))';

export function useConcepts(references: Set<string>) {
// TODO: handle paging (ie when number of concepts greater than default limit per page)
const { data, error, isLoading } = useSWRImmutable<{ data: { results: Array<OpenmrsResource> } }, Error>(
`${restBaseUrl}/concept?references=${Array.from(references).join(',')}&v=${conceptRepresentation}`,
const chunkSize = 100;

export function useConcepts(references: Set<string>): {
concepts: Array<OpenmrsResource> | undefined;
isLoading: boolean;
error: Error | undefined;
} {
const totalCount = references.size;
const totalPages = Math.ceil(totalCount / chunkSize);

const getUrl = (index) => {
if (index >= totalPages) {
return null;
}

const start = index * chunkSize;
const end = start + chunkSize;
const chunk = Array.from(references).slice(start, end);
return `${restBaseUrl}/concept?references=${chunk.join(',')}&v=${conceptRepresentation}&limit=${chunkSize}`;
};

const { data, error, isLoading } = useSWRInfinite<FetchResponse<{ results: Array<OpenmrsResource> }>, Error>(
getUrl,
openmrsFetch,
{
initialSize: totalPages,
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
},
);
return { concepts: data?.data.results, error, isLoading };

const results = useMemo(
() => ({
concepts: data ? [].concat(data?.map((res) => res?.data?.results).flat()) : undefined,
error,
isLoading,
}),
[data, error, isLoading],
);

return results;
}
2 changes: 1 addition & 1 deletion src/utils/form-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export function findConceptByReference(reference: string, concepts) {
} else {
// handle uuid
return concepts?.find((concept) => {
return concept.uuid === reference;
return concept?.uuid === reference;
});
}
}

0 comments on commit 960da66

Please sign in to comment.