I am trying to create a simple table using ReactJS to display user information. Here’s how the general code structure looks like:
class ParentComponent extends React.Component {
state = {
data : ()
}
componentDidMount() {
// initializes state with data from db
axios.get("link/").then(res => {this.setState(data: res.data)});
// I should be able to call this.getData() instead of rewriting the axios.get() function
// but if I do so, my data will not show up
}
// retrieves array of data from db
getData = () => {
axios.get("link/").then(res => {this.setState(data: res.data)});
}
render() {
return (
<div>
<ChildComponent data={this.state.data} refetch={this.getData} />
</div>
)
}
}
Each of the generated rows should have a delete function, where I’ll delete the entry from the database based on a given id. After the deletion, I want to retrieve the latest data from the parent component to be redisplayed again.
class ChildComponent extends React.Component {
// deletes the specified entry from database
deleteData = (id) => {
axios.get("deleteLink/" + id).then(res => {
console.log(res);
// calls function from parent component to re-fetch the latest data from db
this.props.refetch();
}).catch(err => {console.log(err)});
}
render() {
let rows = null;
if(this.props.data.length) {
// map the array into individual rows
rows = this.props.data.map(x => {
return (
<tr>
<td>{x.id}</td>
<td>{x.name}</td>
<td><button onClick={() => {this.deleteData(x.id)}}>Delete</button></td>
</tr>
)
})
}
return (
<div>
<table>
<thead></thead>
<tbody>
{rows}
</tbody>
</table>
</div>
)
}
}
The two problems which I encountered here are:
- Logically, I should be able to call this.getData() from within componentDidMount(), but if I do so, the table doesn’t load.
- Whenever I try to delete a row, the table will not reflect the update even though the entry is removed from the database. The table will only be updated when I refresh the page or delete another row. Problem is, the component is always lagging behind by 1 update.
So far I have tried:
- this.forceUpdate() – doesn’t work
- this.setState({}) – empty setState doesn’t work either
- changing componentDidMount to componentDidUpdate – error showing that I have “reached maximum depth” or something along that line
- adding async await in front of axios – doesn’t work
Any help is appreciated. Thanks in advance.