Reputation: 1201
Fairly new to JS, React. Trying to use Material-table with a add row button. Add row would not add the row. One refreshing the rows are reset. I'm pretty sure I'm doing something wrong with setting/ updating the state.
export default function App() {
return (
<div className="App">
<Tabl
obj={{
a: "a",
items: [{ x: 1 }, { x: 2 }, { x: 3 }]
}}
/>
</div>
);
}
class Tabl extends Component {
constructor(props) {
super(props);
this.state = {
obj: props.obj
};
console.log(JSON.stringify(this.state.obj));
}
updateState(newData) {
this.setState({
obj: [...this.state.obj.items, newData]
});
}
render() {
const currObj = this.state.obj;
const column = [
{
title: "a",
field: "x"
}
];
const tableIcons = {
Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />)
};
return (
<MaterialTable
data={currObj.items}
columns={column}
icons={tableIcons}
options={{
search: false,
paging: false
}}
editable={{
onRowAdd: (newData) =>
new Promise((resolve, reject) => {
setTimeout(() => {
this.updateState(newData);
resolve();
}, 1000);
})
}}
/>
);
}
}
export default Tabl;
Thanks in advance.
Upvotes: 2
Views: 271
Reputation: 87
this.updateState method not binding to class.
You can bind in constructor like this,
constructor(props) {
super(props);
this.state = {
obj: props.obj
};
console.log(JSON.stringify(this.state.obj));
this.updateState= this.updateState.bind(this);
}
Upvotes: 2