Reputation: 111
So my problem here is that my button onClick method is not calling my function.
import React, { Component } from 'react';
import axios from 'axios';
export class FetchData extends Component {
static displayName = FetchData.name;
constructor(props) {
super(props);
this.state = { users: [], loading: true };
}
componentDidMount() {
this.getDataAxios();
}
deleteItem(){
console.log("blabla");
return this.state;
}
editItem = () => {
console.log("asdasd")
}
static renderUsersTable(users) {
return (
<table className='table table-striped' aria-labelledby="tabelLabel">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{users.map(items =>
<tr key="">
<td>{items.id}</td>
<td>{items.name}</td>
<td>{items.age}</td>
<td>
<button type="button" onClick={this.deleteItem} className="btn btn-danger">Delete</button>
</td>
<td>
<button type="button" onClick={this.editItem} className="btn btn-success">Edit</button>
</td>
</tr>
)}
</tbody>
</table>
);
}
render() {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: FetchData.renderUsersTable(this.state.users);
return (
<div>
<h1 id="tabelLabel" >API info</h1>
<p>This component demonstrates fetching data from the api.</p>
{contents}
</div>
);
}
async getDataAxios(){
const response = await axios.get("https://localhost:5001/inventory");
const data = await response.data;
this.setState({ users: data, loading: false });
console.log(data);
} catch(err) {
console.log(err)
}
}
am I maybe doing something wrong with the constructor?
Neither of Edit or Delete buttons are even called when clicked, my console does not log anything at all, neither I get return of the state.
P.S. Some of the property names aren't 100% correct due to the current DATABASE.
Upvotes: 2
Views: 849
Reputation:
Found the solution.
Change
FetchData.renderUsersTable
to
this.renderUsersTable
and remove static
from the renderUsersTable
method. And don't forget to add the bind inside the constructor:
this.deleteItem = this.deleteItem.bind(this);
Upvotes: 2
Reputation:
Change
deleteItem = () => {
to:
deleteItem() {
and add this
bind inside your constructor:
this.deleteItem = this.deleteItem.bind(this);
Upvotes: 1