-
Hi, It's quite easy to have search execution upon clicking submit button or pressing Enter. It's clear why it is so, looking at it from "javascript not enabled in browser" perspective. This is an example of my implementation. I'm having a hidden submit button and clicking it with a 300ms delay after anything is typed. But it feels very wrong for some reason. export default function Search() {
const fetcher = useFetcher<typeof action>()
const ref = useRef<HTMLButtonElement>(null)
let [query, setQuery] = useState('')
let [debouncedQuery] = useDebounce(query, 300)
useEffect(() => {
if (query && query.length > 2 && debouncedQuery && debouncedQuery === query) {
ref.current?.click()
}
}, [query, debouncedQuery])
return (
<>
<fetcher.Form method="post">
<input type="search" name="search" onChange={(e) => setQuery(e.target.value)} value={query} />
<button ref={ref} className="hidden" />
</fetcher.Form>
<Typeahead
isShown={query.length > 2}
isLoading={fetcher.state !== 'idle'}
data={fetcher.data?.items}
clearInput={() => setQuery('')}
/>
</>
)
} Are there any best practices on that? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Instead of clicking the you can use function Search() {
let fetcher = useFetcher<typeof loader>();
let [query, setQuery]= useState("");
let [debouncedQuery] = useDebounce(query, 300)
useEffect(() => {
if (debouncedQuery.length <= 2) return;
fetcher.submit({ search: debouncedQuery })
}, [debouncedQuery]);
return (
<>
<fetcher.Form>
<input
type="search"
name="search"
value={query}
onChange={(event) => setQuery(event.currentTarget.value)}
/>
</fetcher.Form>
<Typeahead
isShown={true}
isLoading={fetcher.state !== "idle"}
data={fetcher.data?.items}
clearInput={() => setQuery("")}
/>
</>
);
} Also note that I'm using a loader instead of action, actions are used for mutations and cause a revalidation of the data after they complete, you don't want to revalidate the data of every route while the user type in the search, and a search is a GET request typically because it's used to read data not mutate it, so a loader is more correct and better for performance. |
Beta Was this translation helpful? Give feedback.
Instead of clicking the you can use
fetcher.submit
to do the request.