I am building a shopping cart which should have the number of cart items automatically updated on the top right corner. Currently the number comes from localStorage, so the page must be reloaded in order to see it working. I need it updated automatically so I think the State is the best approach, but have no idea how to use in this case.
I have created a State in single item (ProductItem component) which is updated for every action "Add to cart".
The current structure is: Home (with CartButton) > Products > ProductItem
How can I pass the single State (ProductItem) to the up level (Products), sum up all single components states, then pass it again to up level (Home), then finally pass as a prop to CartButton?
How can I achieve that? Any help would be greatly appreaciated.
Structure
ProductItem.jsx
import PropTypes from 'prop-types';
import React from 'react';
import { Link } from 'react-router-dom';
class ProductsItem extends React.Component {
constructor() {
super();
this.state = {
qtyState: 1,
};
}
addCart = () => {
const {
title,
thumbnail,
price,
id,
available,
} = this.props;
this.setState((prevState) => ({ qtyState: prevState.qtyState + 1 }));
const cart = localStorage.cart ? JSON.parse(localStorage.cart) : [];
cart.push({
title,
thumbnail,
price,
id,
qtd: 1,
available,
});
localStorage.setItem('cart', JSON.stringify(cart));
}
render() {
const {
title,
thumbnail,
price,
id,
} = this.props;
return (
<div>
<p>{title}</p>
<img src={ thumbnail } alt={ title } />
<p>{ `$ ${price}` }</p>
<button type="button" onClick={ this.addCart }>Add to Cart</button>
</div>
);
}
}
ProductsItem.propTypes = {
title: PropTypes.string,
thumbnail: PropTypes.string,
id: PropTypes.string,
price: PropTypes.number,
available: PropTypes.number,
}.isRequired;
export default ProductsItem;