Home > Enterprise >  react axios get request unable to pass/access response data
react axios get request unable to pass/access response data

Time:06-06

I am trying to create a dynamic list that depends on the amount of items from the backend; using axios get request, I am able to successfully get the data. However, when I try passing the data on to a function or printing the data, it doesn't print out the full data. It only shows the item tag (1, 0...) and when I tried accessing the data itself its giving me undefined.

await axios.get("backend.com/category")
        .then((res) => {
            var result = [];
            //console.log(res.data) shows the array with the actual data
            for (var resdata in res.data) {
                //console.log(resdata) shows only 1 and 0
                result.push(
                    <div>
                        <ItemCards data = {resdata}></ItemCards>
                    </div>
                );
            }

Here are the responses I've gotten:

when logging before mapping :

console.log(res.data)

when logging inside mapping/ItemCards function:

console.log(resdata)

Does anyone know how to fix this? Thank you very much for your time.

CodePudding user response:

change your loop to this one if you want to pass your array data as props to child component:

for (var resdata of res.data) {
    result.push(
      <div>
         <ItemCards data={resdata} />
      </div>
     );
}

  • Related