I want to display list of provinces in select element .I have fetched data from api but I can't display it in select element...I have seen alot about React-Select on the internet But I use CSelect element...This is my code....What's wrong?
const RequestAgency = (props) => {
let provinces = [];
function renderProvinces(){
UserService.getProvince().then(
(response) => {
provinces =response.data ;
provinces.map(province=>{
console.log(province.ItemName)
return <option value={province.ID}>{province.ItemName}</option>
})
}
);
}
return (
<CFormGroup row>
<CCol md="3">
<CLabel htmlFor="province"> province</CLabel>
</CCol>
<CCol xs="12" md="9">
<CSelect custom name="province" id="province" >
{renderProvinces()}
</CSelect>
</CCol>
</CFormGroup>
)
}
export default RequestAgency
CodePudding user response:
It's always best practice to use useState
react hook, to store data and render to page.
I'll suggest you to use the useState
properly, and use useEffect
to get the data from api.
Here I've use the useState
to store data, useEffect
to fetch data from api and use the async/await
for asynchronous api call.
This code seems easy to understand and debugging.
import { useEffect, useState } from "react";
const RequestAgency = (props) => {
const [provinces, setProvinces] = useState([]);
useEffect(() => {
const getData = async () => {
const provinces = await UserService.getProvince()
setProvinces(provinces.data)
};
getData();
}, []);
return (
<CFormGroup row>
<CCol md="3">
<CLabel htmlFor="province"> province</CLabel>
</CCol>
<CCol xs="12" md="9">
<CSelect custom name="province" id="province">
{provinces.map((province, i) => {
return (
<option key={i} value={province.ID}>
{province.ItemName}
</option>
);
})}
</CSelect>
</CCol>
</CFormGroup>
);
};
export default RequestAgency;