how to output axios returned data to screen

Viewed 81

I am successfully returning data from my axios call on page load.

     constructor(props) {
        super(props);
          this.state = {
            myData: []
          }
    }

    componentDidMount() {
    let context= this;
    axios.get('http://localhost:3000/returntestvalues',{
    })
      .then((res) => {
        console.log("Res os: ", res.data)
        context.setState({
          myData: res.data
        });

      })
      console.log("res.data", this.state.myData)
  }

As you can see there, I am setting the State to the returned data. Now, I want to output this into a table:

  render() {
    return (
<body onload="renderData()">
        <table id="customers">
          <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Message</th>
          </tr>
          <tr>
            {this.state.myData?.length > 0
              ? this.state.myData.map((data, index) => (
                  <tr key={index}>
                    <td>{data.name}</td>
                    <td>{data.email}</td>
                    <td>{data.message}</td>
                  </tr>
                ))
              : "No Data Found"}
          </tr>
        </table>
      </body>
    );
  }
}

however, I don't know how to do this through react, I've only ever done it through ejs. Can anyone help?

2 Answers
render() {
    return (
<body onload="renderData()">
        <table id="customers">
          <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Message</th>
          </tr>
          <tr>
            {this.state.myData?.length > 0
              ? this.state.myData.map((data, index) => (
                  <React.Fragment key={index}>
                    <td>{data.name}</td>
                    <td>{data.email}</td>
                    <td>{data.message}</td>
                  </React.Fragment>
                ))
              : "No Data Found"}
          </tr>
        </table>
      </body>
    );
  }
}

Here i am assuming that the keys are name email and message. you can change yours.

You can map your received data like below.

return (
      
      <body onload="renderData()">
      <table id="customers">
      <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Message</th>
      </tr>
{this.state.myData?.length>0 && this.state.myData.map(function(data,index){
return (<tr>
        <td>{data.name}</td>
        <td>{data.email}</td>
        <td>{data.message}</td>
      </tr>);
})}
      

    </table>
    </body>
    );
Related