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:
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