I'm working on a component in my react app that allows for users to select multiple foods in a drop down list. I'm experiencing a problem where the first food item I select is logged as an empty array so every food item I select after that is delayed by one food item. For example, let's say the first food item I select from the dropdown is "Fries", then console.log(foods) will log an empty array. If the second item I select is "Burgers", then the console will log [Fries]. If the third item I select is "Salad", then the console will log [Fries, Burgers]. I'm pretty stuck so any help would be appreciated!
This is where the handle change function is called on the dropdown menu:
<Select
className={classes.dropDownMenu}
options={listItems}
onChange={value => handleChange(value)}
/>
This is my function for handling change on dropdown:
const [foods, setFoods] = React.useState([])
const handleChange = value => {
setFoods(prev => [...prev, value])
console.log(foods)
}
Have you tried to pass the set state of foods like this...
const handleChange = value => {
setFoods(() => [...foods, value])
console.log(foods)
}
that should use the original data and add new data to the state by spreading the original state into the array and adding the value passed in from your Select component.