I'm new in React and I'm trying to write an app working with an API. The code is more extensive so I cut the problem part and put here, I don't know if this is even possible to do, so if someone knows how to do it will be a BIG help.
-Explanation.
When I call deleteProduct()
which I pass by props to the external function listTemplate.js
, the inside getProducts()
gives me this error:
Unhandled Rejection (TypeError): this.getproducts is not a function
export default class test extends Component {
constructor(props) {
super(props);
this.state = {
products: [],
};
}
async componentDidMount() {
this.getproductos();
}
async getproducts() {
const res = await axios.get("http://localhost:5000/api/productos");
this.setState({ products: res.data });
//Set in products info like {products:[name: 'shoes', model:'XXL', price:'90' ]}.
}
async deleteProduct(id) {
await axios.delete("http://localhost:5000/api/productos/" + id); //Delete selected product.
this.getproductos(); //get actualized products array.
}
render() {
const { products } = this.state;
return (
<div className="col-md-6">
<ListTemplate products={products} delBtn={this.deleteProduct} /> //here i pass through listTemplate deleteProduct() function.
</div>
);
}
}
/******************************************************************************/
In another .js file I have this:
export default function ListTemplate(props) {
const { products } = props.product;
return (
<div className="container">
<div className="header">
<h2>Product List:</h2>
</div>
{products.map((product) => (
<div class="body" key={product._id}>
<span>{product.name}</span>
<span>{product.model}</span>
<span>${product.price}</span>
<button
type="button"
class="btn btn-danger btn-sm"
onClick={(e) => {
props.delBtn(product._id);
}}
>
Delete Item
</button>
</div>
))}
</div>
);
}
My problem is when deleteProduct()
finishes and tries to getProduct()
. Explode.