I am using the library material-table for data tables in my application. I was setting the data prop to use data from this.state.data and adding rows would update on my table by using setState. But after switching to remote data the table doesn't update after adding a row. Is there another way to achieve this with remote data?
import React, {Component} from "react";
import MaterialTable from "material-table";
import Add from "@material-ui/icons/Add";
import Clear from "@material-ui/icons/Clear";
import Check from "@material-ui/icons/Check";
import Edit from "@material-ui/icons/Edit";
import FirstPage from "@material-ui/icons/FirstPage";
import ChevronRight from "@material-ui/icons/ChevronRight";
import LastPage from "@material-ui/icons/LastPage";
import ChevronLeft from "@material-ui/icons/ChevronLeft";
import Search from "@material-ui/icons/Search";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends Component {
state = {
data: []
}
render() {
return (
<MaterialTable
columns={[
{
title: "Avatar",
field: "avatar",
render: rowData => (
<img
style={{ height: 36, borderRadius: "50%" }}
src={rowData.avatar}
/>
)
},
{ title: "Id", field: "id" },
{ title: "First Name", field: "first_name" },
{ title: "Last Name", field: "last_name" }
]}
icons={{
Add: () => <Add />,
Check: () => <Check />,
Clear: () => <Clear />,
Edit: () => <Edit />,
FirstPage: () => <FirstPage />,
NextPage: () => <ChevronRight />,
LastPage: () => <LastPage />,
PreviousPage: () => <ChevronLeft />,
ResetSearch: () => <Clear />,
Search: () => <Search />
}}
// If this is an array from state(ie. this.state.data) then it works.
data={query =>
new Promise((resolve, reject) => {
let url = "https://reqres.in/api/users?";
url += "per_page=" + query.pageSize;
url += "&page=" + (query.page + 1);
fetch(url)
.then(response => response.json())
.then(result => {
resolve({
data: result.data,
page: result.page - 1,
totalCount: result.total
});
});
})
}
editable={{
onRowAdd: newData =>
new Promise((resolve, reject) => {
setTimeout(() => {
{
const data = this.state.data;
data.push(newData);
this.setState({ data }, () => resolve());
}
resolve();
}, 1000);
})
}}
title="Remote Data Example"
/>
)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);