I am unable to tel why my table has no data. Is it the way I'm calling for the display, {this.newItems}
or what could it be?
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
taskList: []
};
}
componentDidMount() {
this.refreshList();
}
//refreshList Function start
refreshList = () => {
axios
.get("http://127.0.0.1:8000/list/api/rooms/")
.then(res => this.setState({ taskList: res.data }))
.catch(err => alert(err))
}
//refreshList Function end
//renderItems Function start
renderItems = () => {
const newItems = this.state.taskList;
return newItems.map(item => (
<tr key={item.id}>
<td>{item.thing1}</td>
<td>{item.thing2}</td>
<td>{item.thing3}</td>
</tr>
));
};
//renderItems Function end
render (){
return (
<div>
<Navbar/>
<table className="layout container">
<thead>
<tr>
<th>thing1</th>
<th>thing2</th>
<th>thing3</th>
</tr>
</thead>
<tbody>
{this.newItems}
</tbody>
</table>
<Footer/>
</div>
)
}
}
CodePudding user response:
The reason is that inside <tbody>
tag you are using this.newItems
, which is a local variable and doesn't exist outside the scope of renderItems
function.
The piece of code responsible to render the table data is renderItems
function, which you created but never called.
So you just need to do that:
<tbody>
{this.renderItems()}
</tbody>
Also, inside the renderItems
function, there is no need to create additional variable if you are not going to modify it. So it can be written simply as:
renderItems = () => {
return this.state.taskList.map(item => (
<tr key={item.id}>
<td>{item.thing1}</td>
<td>{item.thing2}</td>
<td>{item.thing3}</td>
</tr>
));
};