0

I am getting the response from an api in this way data:Array(3) 0:"new" 1:"ruby" 2:"ruby"

I want to display this data under a tr element inside a jsx expression. I made a loop to traverse through the array like this

let course = [];
  let userid = this.props.match.params.userid;
  axios.get("someapi") //the api to hit request
   .then((response) => {
    console.log(response);
    for (var i = 0; i < response.data.length; i++) {
     console.log(response.data[i]);
     course.push(response.data[i]);
    }
    console.log("course", course);
    this.setState({ course: course });
    console.log("state course", this.state.course);
   });

I am getting all the values in both console.log, with "course" and "state course" but can't map it inside tbody to display it in tr tag. I want to render it inside this

<tbody>

  <tr>new,ruby and ruby should be displayed here as a list</tr>

</tbody>

What am i doing wrong?

Barry Bonds
  • 118
  • 2
  • 11

2 Answers2

1

Inside of your table

<tbody>
{this.state.course.map(ele => 
   <tr>{ele}</tr>
)}
</tbody>

this should work.

You can also refer to React doc's section: List and Key.

Kerry Gougeon
  • 1,317
  • 12
  • 18
1

If you want all three courses inside the same <tr> tag as a list you could try:

let course = [];
let userid = this.props.match.params.userid;
axios.get("someapi") //the api to hit request
    .then((response) => {
        console.log(response);
        course = response.data.join(", ");
        console.log("course", course);
        this.setState({ course: course });
        console.log("state course", this.state.course);
    });

Then use the course variable in your jsx inside the <tr> tag.

If you want to print one tr for each course set courses equal to response.data and map through it in your jsx

Fecosos
  • 944
  • 7
  • 17