I'm working on an e-commerce project with React where, by clicking on the desired product, it's saved via localStorage.setItem and then always displayed through localStorage.getItem in the cart component. Everything is fine until I go to click another product. It happens that instead of adding it in the cart with the previously selected product, it replaces it. How can I add more than one product?
//component "HomeProduct.js" in which I show the products
export const data = {
"products":[
{
"id": 8,
"img": "img1",
"img2": "img2",
"img3": "img3",
"name": "Product Name1",
"price": 265.90,
"description": "Lorem ipsum dolor sit amet, consectetur."
},
{
"id": 9,
"img": "img1",
"img2": "img2",
"img3": "img3",
"name": "Product Name2",
"price": 695.99,
"description": "Lorem ipsum dolor sit amet, consectetur.",
}
]
}
class HomeProduct extends React.Component{
render(){
return(
<>
{data.products.map((products, key) =>
<Link to={{
pathname: `/Product/${products.id}`,
state: products
}}>
<Button key={key}>
<Image src={products.img}/>
<span>{products.name}</span>
<span>${products.price}</span>
</Button>
</Link>
)}
</>
)
}
}export default HomeProduct;
//"ProductItem.js", component of "Product.js" in in which
//the product details are shown and the button to put it in the cart
class ProductItem extends React.Component{
render(){
const {location} = this.props
function addProductToCart() {
localStorage.setItem('id', location.state.id);
localStorage.setItem('name', location.state.name);
localStorage.setItem('price', location.state.price);
localStorage.setItem('img', location.state.img);
localStorage.setItem('description', location.state.description);
}
return(
<>
<Row id={location.state.id}>
<Col>
<div>
<img src={location.state.img}/>
</div>
<div>
<img src={location.state.img2}/>
</div>
<div>
<img src={location.state.img3}/>
</div>
</Col>
<Col>
<h1>{location.state.name}</h1>
<h1>${location.state.price}</h1>
</Col>
<Col>
<p>{location.state.description}</p>
</Col>
<Button
onClick={addProductToCart}
>Add to Cart</Button>
</Row>
</>
)
}
}export default withRouter(ProductItem);
//"CartProduct.js", component of the cart
export const showProduct = () => {
localStorage.getItem('id');
localStorage.getItem('name');
localStorage.getItem('price');
localStorage.getItem('img');
localStorage.getItem('description');
}
export const CartProduct = () =>(
(localStorage.getItem('id') !== null) ? (
<>
<Row id={localStorage.getItem('id')}>
<Col>
<img src={localStorage.getItem('img')}/>
</Col>
<Col>
<h4>{localStorage.getItem('name')}</h4>
<span>{localStorage.getItem('description')}</span>
<h4>${localStorage.getItem('price')}</h4>
</Col>
<Col>
<Form>
<Form.Row >
<Form.Group>
<Form.Control type="number" defaultValue="1" min="1" count="1"/>
</Form.Group>
</Form.Row>
</Form>
</Col>
</Row>
</>
):(
<span/>
)
)
export default withRouter(CartProduct);
`