Reputation: 3094
I am working with material-ui library and making datatables. For datatable, I am using this library mui-datatables. I need to call an API to retrieve data and show in the table. I checked in the console that data is coming but not showing in datatable.
Below is my code:
state = {
students: [],
rows: []
};
componentDidMount() {
document.title = "List of students";
axios
.get("api.url")
.then(res => {
this.setState({ students: res.data }, () => {
this.state.students.forEach((value, index) => {
this.state.rows.push({
digitalcredid: value.studentid,
firstname: value.firstname,
lastname: value.lastname,
email: value.email,
nationality: value.nationality,
postaladress: value.postaladress,
nic: value.nic
});
});
});
});
}
and showing data like below:
const options = {
filterType: "checkbox",
serverSide: true,
print: false
};
<div className="row">
<div className="col-12">
<MUIDataTable
title={"Student List"}
data={this.state.rows}
columns={studentColumns}
options={options}
/>
</div>
</div>
It would be great if someone help me out.
Upvotes: 1
Views: 3009
Reputation: 5402
You are directly mutating the state to update rows
instead of calling setState
, hence the re-render is not triggered. Try this :
componentDidMount() {
document.title = "List of students";
axios.get("api.url").then(res => {
const rows = [];
res.data.forEach((value, index) => {
rows.push({
digitalcredid: value.studentid,
firstname: value.firstname,
lastname: value.lastname,
email: value.email,
nationality: value.nationality,
postaladress: value.postaladress,
nic: value.nic
});
});
this.setState({ students: res.data, rows });
});
}
From React docs:
setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state.
state
can also be mutated directly like you did above. But that will not trigger a re-render. Hence always update state with setState
if you need the fresh data to be displayed.
Upvotes: 1