PluginProbe
Code Snippets / trunk
Code Snippets vtrunk
4.0.0-beta.2 3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 All 65 releases
code-snippets / js / hooks / useDuplicateReports.ts

useDuplicateReports.ts in Code Snippets trunk, at js/hooks/useDuplicateReports.ts

45 lines 1.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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