Home > Net >  .map the result of an axios get call
.map the result of an axios get call

Time:03-11

I have this data created:

arrayOfObjects = [{"category": "Mainbutton", "description": "Request Data Analysis", "hyperlink": "https://xxx.xxx.xxx.com/display", "sorting": 1, "status": "Online", "title": "Request Data Analysis", "update_date": "22.10.2020"}

and use it with this function to display it:

function MyReactComponent() {

    return (
    <>
      {arrayOfObjects.map(({ title, description }) => (
      <p key={title}>{title} - {description}.</p>
        ))}
    </>
        );
    }

But when I use an Axios API Call with this:

async function axiosTest() {
    const response = await axios.get("ajax/api/mainpage_links")
    console.log(response.data)
    return response.data
}


const arrayOfObjects = axiosTest()


function MyReactComponent() {

    return (
    <>
      {arrayOfObjects.map(({ title, description }) => (
      <p key={title}>{title} - {description}.</p>
        ))}
    </>
        );
    }

I have the following error:

Property 'map' does not exist on type 'Promise'. TS2339

I have googled a lot and cant figure out why it does not work, since my understand is that response.data should work with .map

CodePudding user response:

the async method must be called with await or using .then

arrayOfObjects =await axiosTest()

you must call this method on useEffect() like this:

const [arrayOfObjects ,setData]=useState([]);
useEffect(()=>{
const axiosTest=async()=> {
    let response = await axios.get("ajax/api/mainpage_links")
    console.log(response.data)
    setData(response.data)
}
 axiosTest();
})
  • Related