I'm trying to make a counter that adds up a total amount for items added to a webcart. I initialize this count within my this.state
constructor. However, I'm having problems pushing a count total to it from a function within the same component. This is my Cart
component:
import React, { Component } from 'react';
import {addCart} from './Shop';
import { connect } from 'react-redux';
export class Cart extends Component {
constructor(props) {
super(props);
this.state = {items: this.props.cart,cart: [],total: 0};
}
itemBucket(item) {
this.state.cart.push(this.state.items);
this.countTotal();
}
countTotal() {
console.log(this.state.cart);
this.state.cart.forEach(function(item, index){
var total = this.state.total;
this.state.total = this.state.total + item.price;
})
}
...
render() {
return(
<div className= "Webcart" id="Webcart">
</div>
);
}
}
...
In my countTotal
function I want to push the total to this.state.total
. Right now I'm getting this error Uncaught TypeError: Cannot read property 'state' of undefined
. How can I push the count total to total
in state?