Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display fetched array from api in CSelect element in react

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading