import React, { useEffect, useState } from 'react';
import axios from "axios";
import './List.css';
import { toast } from "react-toastify";
const List = () => {
const url = "http://localhost:4500";
const [list, setList] = useState([]);
const fetchList = async () => {
const response = await axios.get(`${url}/api/food/list`);
console.log("the response data", response.data);
if (response.data.success) {
setList(response.data.data)
}
else {
toast.error("error")
}
}
useEffect(() => {
fetchList();
}, []);
useEffect(() => {
console.log("the list type: ", typeof (list));
}, [list]);
return (
<div className='list add flex-col'>
<p>All food List</p>
<div className="list-table">
<div className="list-table-format title">
<b>Image</b>
<b>Name</b>
<b>Category</b>
<b>Price</b>
<b>Action</b>
</div>
{list.map((item,index)=>{
return(
<div key={index} className="list-table-formate">
<p>{item.name}</p>
</div>
)
})}
</div>
</div>
);
};
export default List;
In the above code I fetch the data from backend using useState([])
empty dependency array using fechList()
function.
The data is fetched successfully. But still the list seems to be empty.
If someone knows the reason, please discuss with me.
I expect the list to be printed in front-end and showing the data properly.
try
/catch
for an error withundefined
is overkill. You need to find the root cause of the error and either fix your code if that is the problem or add handling for cases where the returned data is not defined.