when i try to fetch response from api i got map is not a function error .but i declared state as array.
Here’s the code:
function VendorListScreen(){
const [vendorsList,setVendorsList]=useState([]);
const getVendors =()=>{
axios.get('http://127.0.0.1:8000/api/vendors/').then((res)=>{
setVendorsList(res.data)
})
}
<h1>Vendor</h1>
<button onClick={getVendors}>get</button>
{vendorsList.map(vendor=>{
return <p>{vendor.name}</p>
})}
2
Answers
Verify first if your "res.data" from API return is an array. It’s also possible that your component gets mounted first before the API request gets resolved.
if
api
response returns an array, callmap
after state is updated with data: