71Implement dependent dropdowns with asynchronous options
mediumAbout 35 minutesCodingreactformsasyncrace-conditions
Problem
Build <LocationPicker api={api} onChange={onChange} /> with three <select> elements: name="country", name="state" and name="city". Each one's options depend on the one before:
api.getCountries(),api.getStates(country)andapi.getCities(country, state)each resolve to an array of{ value, label }.- Each select starts with an empty placeholder option (
value="").
Requirements
- Load countries on mount. Load states when a country is chosen, and cities when a state is chosen.
- Choosing a new country resets state and city; choosing a new state resets city.
- A select is disabled while its options load and when its parent has no value.
- If the user switches country quickly, never show the states of the previous country (ignore stale responses).
- Cache option lists: going back to a country you already loaded does not call the API again.
- Call
onChange({ country, state, city })whenever the selection changes.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
{ country, state, city } in a single state value makes resets atomic: choosing a country sets { country, state: "", city: "" } in one update.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.