So I have a component called Products that fetches data from an API endpoint. I also have another component with a form in it and this form is meant to update the products component with the input data and make the new input available to see along with the existing fetched data. How do I accomplish this??...I also passed down the state from the products component to the form component, was this okay??? Your help will be truly appreciated.
Here is my products component:
import React from "react";
import Form from "../Form/form";
import "./products.scss";
class Products extends React.Component {
constructor(props) {
super(props);
this.state = {
products: [],
};
}
componentDidMount() {
fetch("https://codechallenge.pikdrive.com/api/products")
.then((res) => res.json())
.then((res) => {
this.setState({ products: res.data });
});
}
render() {
return (
<div className="products-section">
<h1>Products</h1>
<div className="products-card-container">
{this.state.products.map((product) => (
<div className="products-body">
<div className="products-body-content">
<h4>Id </h4>
<span>{product.id}</span>
<h4>Name </h4> <span>{product.name}</span>
<h4>Description </h4>
<span>{product.description}</span>
<h4>Quantity </h4>
<span>{product.quantity}</span>
</div>
</div>
))}
</div>
<Form data={this.state} />
</div>
);
}
}
export default Products;
Here is my form component:
import "./form.scss";
class Form extends React.Component {
constructor(props) {
super(props);
this.state = this.props.data;
}
render() {
console.log(this.state);
return (
<div className="order-actions-container">
<form className="order-form">
<label>Product Id </label>
<input type="text" placeholder="Enter product id" />
<label>Product Name </label>
<input type="text" placeholder="Enter product name" />
<label>Description </label>
<input type="text" placeholder="Enter product description" />
<label>Quantity</label>
<input type="text" placeholder="Enter product quantity" />
<button type="submit" className="add-button">
Add Item
</button>
</form>
</div>
);
}
}
export default Form;
propsinstate. if you do so yourstatewon't update when thepropsis changed. see: reactjs.org/docs/react-component.html#componentdidmount