|
1
|
--- |
|
2
|
sidebar_label: "useDebouncedSearch" |
|
3
|
--- |
|
4
|
|
|
5
|
import { TypeList } from "docs-ui" |
|
6
|
|
|
7
|
export const metadata = { |
|
8
|
title: `useDebouncedSearch - Admin Components`, |
|
9
|
} |
|
10
|
|
|
11
|
# {metadata.title} |
|
12
|
|
|
13
|
<Note> |
|
14
|
|
|
15
|
This hook is available since Medusa [v2.21.0](https://github.com/medusajs/medusa/releases/tag/v2.21.0). |
|
16
|
|
|
17
|
</Note> |
|
18
|
|
|
19
|
The `useDebouncedSearch` hook manages a search input's value and exposes a debounced copy of it. The Medusa Admin uses it to avoid sending a request to the Medusa backend on every keystroke, such as in the [useComboboxData](../use-combobox-data/page.mdx) hook. |
|
20
|
|
|
21
|
```tsx |
|
22
|
import { useDebouncedSearch } from "@medusajs/dashboard/hooks" |
|
23
|
``` |
|
24
|
|
|
25
|
--- |
|
26
|
|
|
27
|
## Example |
|
28
|
|
|
29
|
Bind `searchValue` to the input and use `query` in the request to the Medusa backend: |
|
30
|
|
|
31
|
```tsx |
|
32
|
import { useDebouncedSearch } from "@medusajs/dashboard/hooks" |
|
33
|
import { Input } from "@medusajs/ui" |
|
34
|
import { useQuery } from "@tanstack/react-query" |
|
35
|
import { sdk } from "../lib/sdk" |
|
36
|
|
|
37
|
const ProductSearch = () => { |
|
38
|
const { searchValue, onSearchValueChange, query } = |
|
39
|
useDebouncedSearch() |
|
40
|
|
|
41
|
const { data } = useQuery({ |
|
42
|
queryKey: ["products", query], |
|
43
|
queryFn: () => sdk.admin.product.list({ q: query }), |
|
44
|
}) |
|
45
|
|
|
46
|
return ( |
|
47
|
<Input |
|
48
|
value={searchValue} |
|
49
|
onChange={(e) => onSearchValueChange(e.target.value)} |
|
50
|
placeholder="Search products" |
|
51
|
/> |
|
52
|
) |
|
53
|
} |
|
54
|
``` |
|
55
|
|
|
56
|
The hook updates `query` 300 milliseconds after the user stops typing, so the query only refetches once for a series of keystrokes. |
|
57
|
|
|
58
|
--- |
|
59
|
|
|
60
|
## Returns |
|
61
|
|
|
62
|
<TypeList |
|
63
|
types={[ |
|
64
|
{ |
|
65
|
name: "searchValue", |
|
66
|
type: "`string`", |
|
67
|
description: "The current value of the search input, updated immediately on every change. Its initial value is an empty string.", |
|
68
|
}, |
|
69
|
{ |
|
70
|
name: "onSearchValueChange", |
|
71
|
type: "`(value: string) => void`", |
|
72
|
description: "A function that sets the search value. Pass it to the input's change handler.", |
|
73
|
}, |
|
74
|
{ |
|
75
|
name: "query", |
|
76
|
type: "`string | undefined`", |
|
77
|
description: "The debounced search value, updated 300 milliseconds after the last change. It's `undefined` when the search value is empty, so that you can pass it directly as a query parameter and omit it when there's no search.", |
|
78
|
}, |
|
79
|
]} |
|
80
|
/> |