bogdy's avatar
Level 10

How to get react-select input selected value to axios data

I have a select input made with react.select

 <AsyncSelect
     cacheOptions
    defaultOptions
      getOptionLabel={e => e.name}
      getOptionValue={e => e.id}
       loadOptions={fetchCustomers}
       onChange={handleChange}
       placeholder="select"
         value={data.customerId}
          name="customerId" 
           id="customerId"
                                    />

for onChange I have this function that delivers the necessary id

 const [selectedValue, setSelectedValue] = useState();
const handleChange = (obj) => {
         return setSelectedValue(obj.id);
    }
    console.log(selectedValue);
```
so far everything is ok. Now I want to deliver the ID in the const [data,setData] to be able to make a post request
```
const [data, setData] = useState({
        name: '',
        description: '',
        customerId: selectedValue,
    })

but for customerId I get undefined

I want to specify that with console.log I can see the id that comes from selectedValue.

What did I do wrong here? thank you in advance

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

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.

Please or to participate in this conversation.