Skip to content

How to populate a repetitive select box?

Posted on:November 16, 2023

You want to populate a select box using server data but wonder what is the best way to do it?

Hard coding the data is not an option because it is too dynamic.

The docs are suggesting to use a fetcher but this means an API call every time the select is rendered which might not be ideal.

useMatches can solve the problem

Load the data in a root loader and use useMatches to access the data in the Select component.

In your root loader get the options and return the in the payload.

root.tsx
export function loader(({request}): DataFunctionArgs) {
const selectOptions = await getCustomSelectOptions(request);
return json({
selectOptions
})
}

Then in the Select component use the data

CustomSelect.tsx
export function CustomSelect() {
const matches = useMatches()
const options = matches.find((match) => match.id === "root").data.selectOptions;
return (
<select>
{options.map(option => (
<option key={option.key} value={option.value}>
{option.title}
</option>
))}
</select>
)
}

This pattern ensures that the data will be fetched only once in the root route and can be consumed all over the app with ease. useMatches lets us access the data of all rendered routes at all times, and in our case, in the select component, wherever it is rendered.

Gotchas:


Subscribe to the newsletter to hear more about these topics!