Reputation: 3
in this react code when I try to access this.state it says it is undefined. I have tried scoping and still the error comes. I want to access this.state.cartItems property to make it add to cart. but it doesn't let me access the property of this.state. It is undefined.
I want to access this.state in below function.
addToCart(product) {
console.log(this.state.products)
console.log('adding to cart ...')
}
import React, { Component } from "react";
import Product from "./../components/client/Product";
import Cart from "./../components/client/Cart";
import data from "./../data.json";
export default class StorePortal extends Component {
constructor() {
super();
}
state = {
products: data.products,
cartItems: []
};
addToCart(product) {
console.log(this.state.products)
//let items = this.state.cartItems.slice();
// let isAdded = false;
// items.forEach((item)=>{
// if(item._id === product._id){
// item.count++;
// isAdded = true;
// }
// if(!isAdded){
// items.push({...product, count: 1});
// }
// })
console.log('adding to cart ...')
}
removeFromCart(product) {
console.log('removing from cart')
}
render() {
return (
<div>
<div className="content">
<div className="main">
<Product
products={this.state.products}
addToCart={this.addToCart}
removeFromCart={this.removeFromCart}
></Product>
</div>
<div className="sidebar">
<Cart cartItems={this.state.cartItems} />
</div>
</div>
</div>
);
}
}
Upvotes: 0
Views: 46
Reputation: 27275
If I understand what you're asking, the problem is that you're doing this: addToCart={this.addToCart}
on the Product component.
The short answer: change it to an inline arrow function:
addToCart={(...args) => this.addToCart(...args)}
The problem with passing the function directly is that you lose the scope; this
no longer points to the component instance. Generally speaking, a function's scope--what this
points to--is bound to the object it was invoked on:
// inside someMethod, "this" will be myObject.
myObject.someMethod()
// invoked independently, "this" is no longer myObject.
const { someMethod } = myObject;
someMethod();
Upvotes: 2