I'm trying to print off SQL data from a get request using axios. I'm using express server-side, and my front end is React. Within my react component, I have a function that has the axios GET call, and then I call that said function within the render. I can get the data fine. My issue is actually printing the data to the table. Here is my code so far:
getTableData(){
axios.get("/api")
.then(function (response){
return(
Object.keys(response).map( (row, index) => (
<TableRow key={index} selected="false">
<TableRowColumn>Test</TableRowColumn>
<TableRowColumn>Test</TableRowColumn>
</TableRow>
))
)
})
.catch(function (error){
console.log(error);
})
}
This is the function I use to do the API call, as well as try to print the table. I call it within the render function as {this.getTabledata()}.
Here is the the get request within my server.js:
app.get('/api', function (req, res){
sql.connect(config, err =>{
new sql.Request().query('select * from Counselling', (err, result) =>{
var table = new Object();
result["recordset"].map( (row, index) => (
table[row["StudentName"]] = row["StudentNumber"]
));
res.send(table);
sql.close();
});
});
Is there something I'm missing? Do I have to use a specific mapping function for the rows?
First of all don't make the api call directly from render method, do that either in componentDidMount lifecycle method or on any specific event. Store the response in state variable because api call will be a asynchronous call, it will not return the ui elements.
Use this to fetch the data from server:
componentDidMount(){
axios.get("/api")
.then( (response) => {
this.setState({response: response})
})
.catch( (error) => {
console.log(error);
})
}
Use this method, it will return the Table rows once you get the response from server, because when we do setState, React render the component again.
getTableData(){
if(!this.state.response) return null; //added this line
return Object.keys(this.state.response).map( (row, index) => (
<TableRow key={index} selected="false">
<TableRowColumn>Test</TableRowColumn>
<TableRowColumn>Test</TableRowColumn>
</TableRow>
))
}