The issue is that useState is only called once when the component is mounted, so data.customerId is not updated when selectedValue changes. To fix this, you can use the useEffect hook to update data.customerId whenever selectedValue changes. Here's an example:
const [selectedValue, setSelectedValue] = useState();
const [data, setData] = useState({
name: '',
description: '',
customerId: null,
});
useEffect(() => {
setData(prevData => ({
...prevData,
customerId: selectedValue,
}));
}, [selectedValue]);
const handleChange = (obj) => {
setSelectedValue(obj.id);
};
console.log(selectedValue);
console.log(data.customerId);
In this example, useEffect is called whenever selectedValue changes. It updates data.customerId by creating a new object with the spread operator and setting the customerId property to selectedValue. Note that prevData is used to ensure that the other properties in data are not overwritten.
Also note that customerId is initially set to null instead of selectedValue to avoid the undefined error.