Idiomatic way to dynamically create HTML select options

I have a form page that has only two HTML select elements: one for states and another for cities. On app load, I am using createResource(...) to make a fetch to my back end server to retrieve a nested list of states where each state has a list of cities. I would like for the city select element to start off empty. The user must first select an option from the state select element. Then the city select element is dynamically populated with results from the createResource(...) call. For populating the state select element, I thought about doing this
<select
id="state"
value={selectedState()}
onChange={(e) => setSelectedState(e.target.value)}
>
<option value="">Select Option</option>
{data().states.map((state) => (
<option value={state.name}>{state.name}</option>
))}
</select>
<select
id="state"
value={selectedState()}
onChange={(e) => setSelectedState(e.target.value)}
>
<option value="">Select Option</option>
{data().states.map((state) => (
<option value={state.name}>{state.name}</option>
))}
</select>
And for populating the city select element, this is what I have
<Show when={selectedState()}>
<select id="city">
<option value=""Select Option</option>
{data().states
.find((s) => s.name === selectedState())
?.cities.map((city) => (
<option value={city.id}>{city.name}</option>
))}
</select>
</Show>
<Show when={selectedState()}>
<select id="city">
<option value=""Select Option</option>
{data().states
.find((s) => s.name === selectedState())
?.cities.map((city) => (
<option value={city.id}>{city.name}</option>
))}
</select>
</Show>
I'm relatively new to Solid.js and was wondering what are the most idiomatic and performant ways to accomplish my goals.
2 Replies
FatFreeButter
FatFreeButterOP2w ago
Additional question: based on my current implementation, are the city options being re-computed every time a re-select the same state? For example: 1) select washington. washington city options are computed 2) select california. california city options are computed 3) select washington again. are washington city options re-computed again?
Madaxen86
Madaxen862w ago
Yes, that’s the default behaviour and it’s absolutely fine. You could also setup a cache (map to store the data by the state keys…) Instead of using a show component you may just disable the select or use css to hide it. Also have a look at the For component for arrays. You could also extract the city data outside the JSX
const cities = () =>{
if (!selectedState() return []
return data().states…
}
const cities = () =>{
if (!selectedState() return []
return data().states…
}

Did you find this page helpful?