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

I want show data in dropdown using api in react js using axios

I want to show data in select option dropdown list using AXIOS .But when I consume data from API it continuously rotate in infinite loop and don’t show data in API.I am using functional component for this.

API data shown in below format:

{
    "status": 1,
    "data": [
        {
            "_id": "62982a3d8779cc4a00139ca0",
            "name": "List Category",
            "status": true,
            "createdAt": "2022-06-02T03:10:53.326Z",
            "updatedAt": "2022-06-02T03:10:53.326Z",
            "__v": 0
        },
        {
            "_id": "62984a1f3cb4c9170532736b",
            "name": "Event Name",
            "status": true,
            "createdAt": "2022-06-02T05:26:55.282Z",
            "updatedAt": "2022-06-02T05:26:55.282Z",
            "__v": 0
        }
    ],
    "message": "List categories list."
}

React Code:

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

const handleInputChange = (value) => {
  setValue(value);
};

// handle selection
const handleChange = (value) => {
  // setSelectedValue(value);
};

const fetchData = () => {
  axios
    .get('http://localhost:5080/list-categories')
    .then((response) => {
      const { data } = response;
      const arrayOfObj = Object.entries(data).map((e) => ({ [e[0]]: e[1] }));
      let tempArray = arrayOfObj.map((item, index) => {
        item.label = item.name;
        item.value = item.name;
        item.id = item.id;
        return item;
      });

      setSelectedValue(tempArray);
    })
    .catch((error) => console.log(error));
};
fetchData();

<select
  disabled={false}
  value={selectedValue}
  onChange={(e) => setSelectedValue(e.currentTarget.value)}
>
  {selectedValue.map(({ label, value }) => (
    <option key={value} value={value}>
      {label}
    </option>
  ))}
</select>;

When I run this code it run in infinite loop and it is not showing any value in dropdown .I just want to show data in dropdown list using API . But this code doesn’t work .Please help me to fix it out. I am new to react. I think I have issue in loop .Please check. I want to show data in select option dropdown list using AXIOS

>Solution :

Try to nest your fetchData call into a useEffect hook call to avoid the loop:

useEffect(() => {
    const fetchData = () => {
        axios
          .get('http://localhost:5080/list-categories')
          .then((response) => {
            const { data } = response;
            const arrayOfObj = Object.entries(data).map((e) => ({ [e[0]]: e[1] }));
            let tempArray = arrayOfObj.map((item, index) => {
              item.label = item.name;
              item.value = item.name;
              item.id = item.id;
              return item;
            });
      
            setSelectedValue(tempArray);
          })
          .catch((error) => console.log(error));
      };
      fetchData();
}, []);

Also, try to add a conditional check to wait for the data to be loaded:

<select
  disabled={false}
  value={selectedValue}
  onChange={(e) => setSelectedValue(e.currentTarget.value)}
>
  {!selectedValue ? (
    <>Loading data...</>
  ) : selectedValue.length === 0 ? (
    <>No data found</>
  ) : (
    selectedValue.map(({ label, value }) => (
      <option key={value} value={value}>
        {label}
      </option>
    ))
  )}
</select>;
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