skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. if api response returns an array, call map after state is updated with data:

     <button onClick={getVendors}>get</button>
        {vendorsList && vendorsList.map(vendor=>{
            return <p>{vendor.name}</p>
        })}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search