0

i use axios to get values, now i want to display the values in td tag in a loop how to execute it.

my code is :

let apiUrl = "http://api_url_here";
axios.get(apiUrl, {headers: headers})
  .then((response) => {
    console.log(response.data[0].provider.firstName);
    //console.log(token);[0]
  })

My td code is:

<tr>
  <td className="font-weight-medium"> <img className="logo" src={jessica} alt="pam-logo" /> </td>
  <td>[email protected] </td>
  <td>(012)-876789876</td>
  <td>Family Physician</td>
  <td>23145655</td>
  <td>Mountain view,Ave</td>
  <td><Icon icon={editIcon} width="20px"/>&nbsp;&nbsp;<Icon icon={deleteIcon} width="20px"/></td>
</tr>

I need that response.data[0].provider.firstName in 1st td and correspondingly the same for all and it should be in loop to get next iteration.

4
  • Are you using class component for this? Commented Feb 19, 2020 at 11:29
  • @MuhammadZeeshan yes Commented Feb 19, 2020 at 11:30
  • 1
    Can you show the value of response.data? Commented Feb 19, 2020 at 11:30
  • @MuhammadZeeshan its only a json object with name,mail etc Commented Feb 19, 2020 at 11:37

3 Answers 3

1

try this.

import React, {useState, useEffect} from 'react'

const myFunction = () => {
  const [ data, setData ] = useState(null)

  const apiUrl = "http://api_url_here"

  useEffect(() => {
    axios.get(apiUrl, {headers: headers})
      .then((response) => {
         setData(response.data)
      })
  }, [])


  return (
    <>
      {
        data && data.map((item, index) => (
          <tr key={index}>
            <td>{item.provider.firstName}</td>
            ...
          </tr>
        ))
      }
    </>
  )
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your axios call should ordinarily be in an initialization stage, such as by employing useEffect or componentDidMount, depending on the style of your component.

Then you set the data using your response, e.g.

setData(response.data); 

or

this.setState({"myData": response.data});

and in your render, you use that data loop to generate the rows, something along the lines of:

const { myData } = this.state;
myData.map((datum, index) => {
   <tr key={index}>
     <td>{datum.provider.firstName}</td>
     ...
   </tr>
});

1 Comment

No its not working, show datum and index is not defined error
0

If response.data is the list with your table content, add this to your render() method:

return response.data.map((item, index) => {
   <tr key={index}>
      <td>{item.foo}</td>
      <td>{item.bar}</td>
      ...
   </tr>
});

1 Comment

Was missing a (, fixed now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.