I call an axios delete method in child component and want to refresh the parent component to react. When delete() called it deleted the row from database but it needs to reload manually. How could I do that without manual reloading?
I want to delete method works and the ProductList.js also update at the same time.
import React, { Component } from "react";
import axios from "axios";
import Table from "./Table";
class ProductList extends Component {
constructor(props) {
super(props);
this.state = { productData: [] };
}
componentDidMount() {
axios
.get("http://localhost:8080/products")
.then((response) => {
console.log("responseProductList==", response);
this.setState({ productData: response.data });
})
.catch(function (error) {
console.log(error);
});
}
tabRow() {
return this.state.productData.map(function (object, i) {
return <Table obj={object} key={i} />;
});
}
render() {
return (
<div style={{ paddingTop: "25px" }}>
<h4 align="center">Product List</h4>
<table className="table table-striped" style={{ marginTop: 10 }}>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th colSpan="4">Action</th>
</tr>
</thead>
<tbody>{this.tabRow()}</tbody>
</table>
</div>
);
}
}
export default ProductList;
import React, { Component } from "react";
import axios from "axios";
import { Link, withRouter } from "react-router-dom";
// import ProductList from "./ProductList";
// import AddProduct from "./AddProduct";
class Table extends Component {
// constructor(props) {
// super(props);
// }
deleteProduct = () => {
console.log("delete button clicked");
axios
.delete("http://localhost:8080/products/" + this.props.obj.id)
.then((res) => {
if (res.status === 200) {
alert("getStatusInDelete");
// return axios.get("http://localhost:8080/products/");
// this.forceUpdate(<ProductList />);
this.props.history.push("/ProductList");
} else {
console.log("Not refresh");
}
})
.catch((err) => console.log(err));
};
render() {
return (
<tr>
<td>{this.props.obj.id}</td>
<td>{this.props.obj.name}</td>
<td>{this.props.obj.price}</td>
<td>
<Link
to={"/EditProduct/" + this.props.obj.id}
className="btn btn-success"
>
Edit
</Link>
</td>
<td>
<button
type="button"
onClick={this.deleteProduct}
className="btn btn-danger"
>
Delete
</button>
</td>
</tr>
);
}
}
export default withRouter(Table);