I would like to understand why is it when I'm switching between posts, the input fields are not changing their values, even though each product object has different name and description property.
Further explanation: When clicking on each ProductView (Product Component) a new window is shown with details on that product that could be changed and saved (name and description) through input fields. but when switching between products (by clicking on different products) the text on these input fields do not change.
example product object: product = { name: 'product 1', desc: 'product 1 desc' }
this is the code:
// Main Store Component
const Store = () =>{
const [prods, setProducts] = useState([...products]);
const[show, showDetails] = useState(false);
const[productToShow, setProductToShow]=useState();
function onSaveProduct(newProduct){
let i = prods.findIndex((x)=> x['id']===newProduct.id);
prods[i] = newProduct;
setProductToShow(newProduct)
setProducts([...prods]);
}
return(<div className={'flex-container'}>
<Container className="store-container">
<div className={'column-align'}>
{([...prods]).map((pro)=>{
return <Product key={pro.id} product={pro} showDetails={showDetails}
setProductToShow={setProductToShow}/>
})}
</div>
</Container>
{show && <ProductToShow product={productToShow} onSave={onSaveProduct}/>}
</div>);
}
// Product component
const Product = ({product, setProductToShow, showDetails, deleteFromList}) =>{
const handleClick = () =>{
setProductToShow(product);
showDetails(true);
}
return (
<div className="product-container">
<div className="name-desc"onClick={handleClick}>
<h3>{product.name} </h3>
<h5>{product.desc}</h5>
</div>
</div>
);
}
// ProductToShow functional component
const ProductToShow = ({product, onSave}) =>{
const nameInput = useFormInput(product.name);
const descInput = useFormInput(product.desc);
const newProduct = {
id: product.id,
name: nameInput.value,
desc: descInput.value,
};
function useFormInput(initialValue){
const[value, setValue] = useState(initialValue);
function handleChangeEvent(e){
setValue(e.target.value);
}
return{
value: value,
onChange: handleChangeEvent
}
}
return (
<div className="to-show-container">
<h1>{product.name}</h1>
<label>Product Name: </label>
<input {...nameInput}/>
<label>Product Description: </label>
<input {...descInput}/>
<div className={'to-the-right'}>
<Button onClick={()=>onSave(newProduct)}>Save</Button>
</div>
</div>
);
}
screenshot (Product 3 is clicked, but the details of Product 1 is shown in the input fields):
