| 1 |
import { useEffect, useState } from 'react' |
| 2 |
import { addQueryArg } from '../utils/restAPI' |
| 3 |
import { useRestAPI } from './useRestAPI' |
| 4 |
import type { DuplicateReport, DuplicateSearchResponse } from '../types/Feedback' |
| 5 |
|
| 6 |
/** Shortest title worth looking for existing reports of. */ |
| 7 |
const MIN_SEARCH_LENGTH = 6 |
| 8 |
|
| 9 |
/** How long to wait after the last keystroke before searching. */ |
| 10 |
const SEARCH_DEBOUNCE_MS = 600 |
| 11 |
|
| 12 |
/** |
| 13 |
* Offer reports already filed about whatever is being described, so the same problem is |
| 14 |
* not reported twice. A cloud that cannot answer leaves the list empty rather than |
| 15 |
* interrupting the report being written. |
| 16 |
*/ |
| 17 |
export const useDuplicateReports = (searchUrl: string, title: string): DuplicateReport[] => { |
| 18 |
const { api } = useRestAPI() |
| 19 |
const [duplicates, setDuplicates] = useState<DuplicateReport[]>([]) |
| 20 |
|
| 21 |
useEffect(() => { |
| 22 |
const query = title.trim() |
| 23 |
|
| 24 |
if (MIN_SEARCH_LENGTH > query.length) { |
| 25 |
setDuplicates([]) |
| 26 |
return |
| 27 |
} |
| 28 |
|
| 29 |
let active = true |
| 30 |
|
| 31 |
const timer = setTimeout(() => { |
| 32 |
api.get<DuplicateSearchResponse>(addQueryArg({ url: searchUrl, name: 'q', value: query })) |
| 33 |
.then(data => active && setDuplicates(data.results)) |
| 34 |
.catch(() => active && setDuplicates([])) |
| 35 |
}, SEARCH_DEBOUNCE_MS) |
| 36 |
|
| 37 |
return () => { |
| 38 |
active = false |
| 39 |
clearTimeout(timer) |
| 40 |
} |
| 41 |
}, [api, searchUrl, title]) |
| 42 |
|
| 43 |
return duplicates |
| 44 |
} |
| 45 |
|