Here is my basic implementation of a Select component with server-side searches inside FormField:
export default function AddProduct() {
const [form, setForm] = useState({ category_id: '' })
const [categories, setCategories] = useState([])
const onSearch = string => {
const makeRequest = async () => {
const term = string && string.length ? string.trim() : ''
const options = { q: term, 'per-page': 1 }
// Requesting categories based on user's search.
const res = await API().categories.fetchMany(options)
try {
const json = await res.json()
// Updating the categories list on-the-fly from server-side response.
setCategories(json.data)
} catch (e) {
// ...
}
}
makeRequest()
}
return (
<Box>
<Form
value={form}
onChange={nextForm => setForm(nextForm)}
>
<FormField
name='category_id'
htmlFor='input-categories'
label='Categories'
>
<Select
name='category_id'
// Dispatches the first request (usability only) in order to prevent
// user from viewing an empty list.
onOpen={onSearch}
onSearch={onSearch}
// Options are always the filtered list from server-side.
options={categories}
labelKey="name"
valueKey={{ key: 'id', reduce: true }}
/>
</FormField>
</Form>
</Box>
)
}
Expected Behavior
I expected users to search & select options indefinitely without selected option becoming blank when it's not present in the options array.
Actual Behavior
If users search for a category and choose then it is correctly displayed as the selected options BUT when the user search again and the selected option doesn't appears on the server-side result (in other words, not in the options list) then the selected option becomes blank.
1. Here I'm intentionally rendering only one result per search.
2. First, I select "Tijolo" category.
3. Then I change to "Ferro".
4. Last step I opened the select dropdown again, which dispatches a request "onOpen" event, and "Ferro" is not present in the results page then it's option becomes blank.
As I can see now, "onSearch" events doesn't appears to make it blank but "onOpen" does. I'm wondering why (?).
Does anyone have an idea on how to deal with "onOpen" and "onSearch" events rendering dynamic options in a grommet Select component?
Grommet version: 2.17.2