I was going to build autocomplete using remix.run, but then it occurred to me that would be relying too much on routing and forms to select/focus the input after each submit, this can not produce good UX. The user will input something into form, the form gets submitted, he awaits response, and then the input is focused again, and the ux here that this is instantsearch/autocomplete.
What you need is the useFetcher hook Remix exports. This hook let you fetch data from the loader of any route without causing a navigation, it was added for this kind of UIs.
import { Form, useFetcher } from "remix"
export default function Screen() {
let fetcher = useFetcher()
function handleChange(event) {
let value = event.currentTarget.value
// load data from a route with a loader
fetcher.load(`/api/autocomplete?query=${value}`)
}
return (
<Form>
<input type="text" onChange={handleChange} list="suggestions" />
<datalist id="suggestions">
{fetcher.data.map(item => {
return <option key={item.id} value={item.value} />
})}
</datalist>
</Form>
)
}
Something like that, and in the endpoint you load with the fetcher you export a loader
export async function loader({ request }) {
let url = new URL(request.url)
let query = url.searchParams.get("query") ?? "";
let data = await getData(query)
return json(data)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With