I am building my frontend using react app
I want when the user select a bank it will be added to the selectData state.
But it is not working as expected
when the user is selects a bank for the first time it does not add to the selectedData state but if the user select the second time it is added to the state
import React, { useState } from 'react'
export const terr = () => {
const [selectedData, setSelectedData] = useState({})
const onChange = (value) => {
console.log(`selected ${value}`);
setSelectedData({
...selectedData,
"bank_code": value
});
console.log(`selected data ${selectedData}`);
};
return (
<div>
<Form.Item
label="Bank Name"
name="bank_code"
rules={[
{
required: true,
message: 'Select your bank name!',
},
]}
>
<Select
showSearch
placeholder="Select a Bank"
optionFilterProp="children"
onChange={onChange}
onSearch={onSearch}
filterOption={filterOption}
options={banks}
/>
</Form.Item>
</div>
)
}
2
Answers
In React the setState function won’t update the state until the next render. To get it to update immediately you can use a callback in the setSelectedData function.
Within
onChange
, the object thatselectedData
is bound to doesn’t change. Instead react will re-render theterr
, and that will see the new object that you passed tosetSelectedData
, and you will have a newonChange
that will close over it. As you note, a call to thatonChange
will see the modifiedselectedData
.If you want to observe that object, give it a name before passing it to
setSelectedData
.