I'd like to return the entire object representation of an item in a list, however, when a selection is made and handleChangeSelectAuto
is called the original value from useState
is returned, and from there forward the previous selected value is always returned.
How can I select an item from a list and return all its associated data?
import React, { useEffect, useState } from 'react';
import { FormControl, InputLabel, Select, MenuItem } from '@mui/material';
interface AutoSelectorProps {}
const AutoSelector: React.FC<AutoSelectorProps> = () => {
const [auto, setAuto] = useState({} as object);
const [autoName, setAutoName] = useState('' as string);
const [autoList, setAutoList] = useState([
{
id: 1,
name: 'Car',
color: 'red'
},
{
id: 2,
name: 'Truck',
color: 'blue'
},
]);
const handleChangeSelectAuto = async (value: string) => {
const index = autoList.findIndex((item) => {
return item.name === value;
});
setAutoName(value);
setAuto(autoList[index]);
console.log(auto);
// 1st log: {}
// 2nd log: object from previous selection
// 3rd log: object from previous selection, etc.
};
return (
<div>
<FormControl>
<InputLabel>Select Auto</InputLabel>
<Select
value={autoName}
label="Auto"
onChange={(e) => handleChangeSelectAuto(e.target.value as string)}
>
{autoList.map((item) => {
return (
<MenuItem key={item.name} value={item.name}>
{item.name}
</MenuItem>
);
})}
</Select>
</FormControl>
</div>
);
};
export default AutoSelector;
P.S. If I add a button and handler to log auto
it will return the correct value, but I'm not seeing a race condition.
CodePudding user response:
useState is asynchronous. It will not show the values immediately. use useEffect
to see the updated values
useEffect(() => {
console.log(auto);
}, [auto])