Home > Enterprise >  Looping React Axios result
Looping React Axios result

Time:05-23

my purpose is to printout http request´s result set. I don´t know what is the working way to loop with this result.

 const result = await axios.get("http...");
[
  {
    "A": "SSS NNN",
    "B": "TEXT SSSS",
  },
  {
    "A": "text ttttt",
    "B": "text ttttt",
  }
]
 

CodePudding user response:

You can try this way

return <>
{
  result.map((r, id) => {
     return <div key={id}>{r.A} {r.B}</div>
  }) 
}
</>

Here we capture id because react needs a key prop for every child item to keep track of them internally.

CodePudding user response:

Axios returns an object with multiple nested objects but the result of the api is stored in the data object.

So if you want to access the data object from axios there are two ways.
1.) Accessing through result object

const result = await axios.get("http...")

result.data.map((res, id) => {
  return <div key={id}>{res.A} {res.B}</div>
}) 

2.) You can destructure the data object from api request

const { data } = await axios.get("http...")

data.map((res, id) => {
  return <div key={id}>{res.A} {res.B}</div>
}) 
  • Related