Skip to content

Commit eb4a474

Browse files
author
Peter Bengtsson
authored
refactory getting 'query' with a hook (#22879)
1 parent 7f3a746 commit eb4a474

2 files changed

Lines changed: 32 additions & 5 deletions

File tree

components/Search.tsx

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { useTranslation } from 'components/hooks/useTranslation'
77
import { sendEvent, EventType } from 'components/lib/events'
88
import { useMainContext } from './context/MainContext'
99
import { useVersion } from 'components/hooks/useVersion'
10+
import { useQuery } from 'components/hooks/useQuery'
1011
import { useLanguages } from './context/LanguagesContext'
1112

1213
import styles from './Search.module.scss'
@@ -36,10 +37,7 @@ export function Search({
3637
children,
3738
}: Props) {
3839
const router = useRouter()
39-
const query =
40-
router.query.query && Array.isArray(router.query.query)
41-
? router.query.query[0]
42-
: router.query.query || ''
40+
const { query, debug } = useQuery()
4341
const [localQuery, setLocalQuery] = useState(query)
4442
const [debouncedQuery, setDebouncedQuery] = useDebounce<string>(localQuery, 300)
4543
const inputRef = useRef<HTMLInputElement>(null)
@@ -185,7 +183,7 @@ export function Search({
185183
isLoading={isLoading}
186184
results={previousResults}
187185
closeSearch={closeSearch}
188-
debug={'debug' in router.query}
186+
debug={debug}
189187
query={query}
190188
/>
191189
</div>

components/hooks/useQuery.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { useRouter } from 'next/router'
2+
3+
type QueryInfo = {
4+
query: string
5+
debug: boolean
6+
}
7+
export const useQuery = (): QueryInfo => {
8+
const router = useRouter()
9+
const query =
10+
router.query.query && Array.isArray(router.query.query)
11+
? router.query.query[0]
12+
: router.query.query || ''
13+
14+
let debug = false
15+
if (router.query.debug) {
16+
// Now `router.query.debug` is either string or any array of strings
17+
debug = Boolean(
18+
JSON.parse(Array.isArray(router.query.debug) ? router.query.debug[0] : router.query.debug)
19+
)
20+
} else if (router.query.debug === '') {
21+
// E.g. `?query=foo&debug` should be treated as truthy
22+
debug = true
23+
}
24+
25+
return {
26+
query,
27+
debug,
28+
}
29+
}

0 commit comments

Comments
 (0)