I have a list of products (unordered list which I apply at the beginning and it shows on screen) and after click on one of them for example: milk, app should add it on screen to list "to buy". But it shows on the screen after I click on another element or second time on the first one. It also not working when I only console.log() in addProduct
import React from "react";
import commonColumnsStyles from "../../common/styles/Columns.module.scss";
class ProductsList extends React.Component {
constructor(props) {
super(props);
this.state = { productsToBuy: [] };
this.addProduct = this.addProduct.bind(this);
}
addProduct(index) {
let newProduct = [
this.props.productsToDisplay.filter(
(currEl, currIndex) => currIndex === index
),
];
this.setState({
productsToBuy: this.state.productsToBuy.concat(newProduct),
});
this.props.sendAddedProductsToParent(this.state.productsToBuy);
console.log(this.state.productsToBuy);
}
render() {
return (
<div className={commonColumnsStyles.App}>
<header className={commonColumnsStyles.AppHeader}>
<p>Products list</p>
<ul>
{this.props.productsToDisplay.map((currProduct, index) => (
<li key={index} onClick={() => this.addProduct(index)}>
{currProduct.nazwa}
</li>
))}
</ul>
</header>
</div>
);
}
}
export default ProductsList;
I have tried setState (in function addProduct) with .concat. It appears immediately when I've used .push method but after click on second element this.state.productsToBuy.push is not a function.
After all I display this products by map method in another function component.
CodePudding user response:
setState
is an async operation. this.state.productsToBuy
is not
updated until the next render. Save the result of the concat
in a local variable and pass it to sendAddedProductsToParent
instead.
CodePudding user response:
Does this work for you:
addProduct(index) {
const toBuy = Array.from(this.state.productsToBuy);
toBuy.push(this.props.productsToDisplay[index]);
this.setState({productsToBuy: toBuy});
this.props.sendAddedProductsToParent(toBuy);
console.log(toBuy);
}
CodePudding user response:
addProduct(index) {
const toBuy = Array.from(this.state.productsToBuy); toBuy.push(this.props.productsToDisplay[index]);
this.setState({productsToBuy: toBuy}); this.props.sendAddedProductsToParent(toBuy);
console.log(toBuy); }