Reputation: 3600
When I click on the button [Add to Cart] I'm getting an error:
.
How should I fix that?
Here's my full code link, and below is an abstract, that is relevant to question:
class ProductsList extends Component {
....
renderProductsList() {
function mapProductCards(elem) {
return (
<Card className="m-1" style={{width: '18rem'}} key={elem.id}>
....
<CardText>isAvailable</CardText>
<Button onClick={() => this.props.addItemToCart(elem.id)}>Add to Cart</Button>
</CardBlock>
</Card>
)
}
....
this.props.products ....
.map(mapProductCards)
....
const mapDispatchToProps = (dispatch) => ({
....
addItemToCart(value) {
dispatch(addToCart(value));
}
....
});
export default connect(mapStateToProps, mapDispatchToProps)(ProductsList);
....
Upvotes: 1
Views: 155
Reputation: 59491
At the start of your renderProductsList function, assign your this
variable to a local one. Like this:
renderProductsList() {
var that = this;
function mapProductCards(elem) {
return (
and then just use that
where needed. For example, your button would now be:
<Button onClick={() => that.props.addItemToCart(elem.id)}>Add to Cart</Button>
Alternatively, use an arrow function instead. Like this:
renderProductsList() {
mapProductCards = (elem) => {
return (
this will preserve the reference of this
to the object you actually need.
EDIT
After looking at your full code, based on how you use your mapProductCards
function, you need to pass in the correct object to use as this
. You can pass that object as the second parameter to your map
. Like this:
this.props.products.map(mapProductCards, this);
You might find the documentation for map()
over at MDN interesting:
var new_array = arr.map(function callback(currentValue, index, array) { // Return element for new_array }[, thisArg])
thisArg: Optional. Value to use as this when executing callback.
Upvotes: 1
Reputation: 2771
I also faced this issue and the problem was when i debugged my code ,local this ie this object of the function was giving undefined object.you need to instantiate this object of the function addItemToCart because when you click the button it will give you an error on console saying
Your method addItemToCart is undefined to overcome this you need to define local this as
renderProductsList() {
var localThis= this;
}
and then call your method as
onClick={() => localThis.props.addItemToCart(elem.id)}
If you are using a function inside a loop say map then you need to do
this.state.map(function(){
},**this**)
to preserve this
Upvotes: 1