I am trying to make 3 select dropdowns automatically change based on the selection. First dropdown has no dependencies, 2nd depends on first, and 3rd depends on 2nd.
This is a very simplified version of my code:
// record, onSave, planets, countries, cities passed as props
const [selectedPlanet, setSelectedPlanet] = useState(record.planet);
const [selectedCountry, setSelectedCountry] = useState(record.country);
const [selectedCity, setSelectedCity] = useState(record.city);
const filteredCountries = countries.filter(c => c.planet === selectedPlanet.id);
const filteredCities = cities.filter(c => c.country === selectedCountry.id);
return (
<div>
<select value={selectedPlanet.id} onChange={(e) => setSelectedPlanet(e.target.value)}>
{planets.map(p => (
<option key={p.id} value={p.id} name={p.name} />
)}
</select>
<select value={selectedCountry.id} onChange={(e) => setSelectedCountry(e.target.value)}>
{filteredCountries.map(c => (
<option key={c.id} value={c.id} name={c.name} />
)}
</select>
<select value={selectedCity.id} onChange={(e) => setSelectedCity(e.target.value)}>
{filteredCities.map(c => (
<option key={c.id} value={c.id} name={c.name} />
)}
</select>
<button onClick={() => onSave({planet: selectedPlanet, country: selectedCountry, city: selectedCity ) }
</div>
);
The select options will update accordingly, but onSave() will receive outdated values for country and city if I select a planet and click the save button.
That is because setSelectedCountry and setSelectedCity are not called on planet change. I know I can just call them in that event, but it would make the code much uglier because I would have to duplicate the country and city filtering. Is there a better way around this?