I’m creating a simple select dropdown form in React using Bootstrap. The options in the dropdown are populated from an array of "region" objects retrieved from the app’s database. My problem is that when I click on an options from the dropdown, the first item click console logs a 404 error from the api. The second click console logs the first item I clicked on, the third click shows the second item I clicked on and so on, so that every click yields the data for the previous item clicked on.
The form I’m using:
<Form>
<select class="form-control" onChange={handleRegionChange} >
<option>Select a Region</option>
{regions.map((region) =>
<option
value= {region.id}
key={region.id}
>
{region.country}
</option>
)}
</select>
</Form>
The handleRegionChange function I’m using looks like this. Note, that even without the additional retrieveRegion step on the third line to get the region using the id passed from the form, I still have the same issue. The console log shows null for the id of the first item clicked on, then the id for the previous item, etc.
const handleRegionChange = (e) => {
setRegionId(e.target.value);
retrieveRegion(regionId)
console.log(regionId)
}
Here’s the setup for my functions:
const [regions, setRegions] = useState([]);
const [currentRecipe, setCurrentRecipe] = useState(initialRecipeState);
const [regionId, setRegionId] = useState()
const [currentRegion, setCurrentRegion] = useState ()
const [regionRecipe, setRegionRecipe] = useState(initialRegionRecipeState);
useEffect(() => {
retrieveRegions();
retrieveRecipe(id);
}, []);
Screenshots with data displayed after clicking on select option to demonstrate the problem. First I click on Mexico and it shows France, then I click on the US and it shows Mexico. Again, this problem also occurs when I simply try to console log the id from the value of the option selected.
Summary:
I tried to create a dropdown select form from an array of objects. I expected to be able to click on one of the options in the dropdown form and get the value of the id associated with that item. Instead I keep getting the value of the id for the previously selected option.
2
Answers
State updates in React are asynchronous; when an update is requested, updates will not be made immediately.
But you can track the state changes in the useEffect hook.