I want to set default value for react-select when I open particular request which I get from API. Cities
options for my select are too from API and they work well.
const [request, setRequest] = useState<IRequest>();
const [cities, setCities] = useState<ICity[]>([]);
const [defaultCity, setDefaultCity] = useState({});
useEffect(() => {
axios.get<IRequest>('/api/requests/' id)
.then((res) => {
setRequest(res.data)
setDefaultCity({ value: res.data.city.code, label: res.data.city.name })
})
axios.get<ICity[]>('/api/cities')
.then(res => setCities(res.data))
}, [])
Here is my select
<Select
placeholder='City'
defaultValue={defaultCity}
options={
cities.map(city => (
{ value: city.code, label: city.name }
))
}
/>
If I console.log when submitting form defaultCity
is what I want (because of asynchronous I guess).
Request
object looks like this
{
"id": 1,
"status": {
"code": "DRAFT"
},
"city": {
"code": "MSC",
"name": "Moscow"
}
}
CodePudding user response:
I faced a similar kind of issue. An elegant way to solve it to set option value prior.
<option value={defaultCity.value && ''}>{defaultCity?.label}</option>