diff --git a/frontend/src/services/comboboxItemService.ts b/frontend/src/services/comboboxItemService.ts index 77197cb36a..c06e8c2051 100644 --- a/frontend/src/services/comboboxItemService.ts +++ b/frontend/src/services/comboboxItemService.ts @@ -113,6 +113,45 @@ type ComboboxItemService = { ) => (filter?: string) => Promise> } +// Function to debounce the actual HTTP request +function debounce( + func: ( + endpoint: Endpoint, + filter?: string, + size?: number, + ) => Promise>, + delay: number, +) { + let timeoutId: NodeJS.Timeout + + return async function ( + endpoint: Endpoint, + filter?: string, + size?: number, + ): Promise> { + clearTimeout(timeoutId) + + return new Promise>(async (resolve) => { + timeoutId = setTimeout(async () => { + const result = await func(endpoint, filter, size) + resolve(result) + }, delay) + }) + } +} + +// Debounced version of the fetchFromEndpoint function +const debouncedFetch = debounce(fetchFromEndpoint, 400) // Set your desired delay in milliseconds + +async function fetchFromEndpointDebounced( + endpoint: Endpoint, + filter?: string, + size?: number, +) { + return debouncedFetch(endpoint, filter, size) +} + +// Modify your service to use the debounced function const service: ComboboxItemService = { filterItems: (items: ComboboxItem[]) => (filter?: string) => { const filteredItems = filter @@ -121,19 +160,22 @@ const service: ComboboxItemService = { return Promise.resolve({ status: 200, data: filteredItems }) }, getCourts: async (filter?: string) => - await fetchFromEndpoint(Endpoint.courts, filter), + await fetchFromEndpointDebounced(Endpoint.courts, filter), getDocumentTypes: async (filter?: string) => - await fetchFromEndpoint(Endpoint.documentTypes, filter), + await fetchFromEndpointDebounced(Endpoint.documentTypes, filter), getFieldOfLawSearchByIdentifier: async (filter?: string) => - await fetchFromEndpoint(Endpoint.fieldOfLawSearchByIdentifier, filter), + await fetchFromEndpointDebounced( + Endpoint.fieldOfLawSearchByIdentifier, + filter, + ), getRisAbbreviations: async (filter?: string) => - await fetchFromEndpoint(Endpoint.risAbbreviations, filter), + await fetchFromEndpointDebounced(Endpoint.risAbbreviations, filter), getRisAbbreviationsAwesome: async (filter?: string) => - await fetchFromEndpoint(Endpoint.risAbbreviationsAwesome, filter), + await fetchFromEndpointDebounced(Endpoint.risAbbreviationsAwesome, filter), getCitationTypes: async (filter?: string) => - await fetchFromEndpoint(Endpoint.citationTypes, filter), + await fetchFromEndpointDebounced(Endpoint.citationTypes, filter), getProcedures: async (filter?: string) => - await fetchFromEndpoint(Endpoint.procedures, filter, 10), + await fetchFromEndpointDebounced(Endpoint.procedures, filter, 10), } export default service