PluginProbe
Code Snippets / 4.0.0-beta.3
Code Snippets v4.0.0-beta.3
4.0.0-beta.3 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 All 66 releases
code-snippets / js / hooks / useDuplicateReports.ts

useDuplicateReports.ts in Code Snippets 4.0.0-beta.3, at js/hooks/useDuplicateReports.ts

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