1

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?

feners
  • 645
  • 5
  • 19
  • 48
  • Possible duplicate of [React 'cannot read property of undefined' despite correct binding](https://stackoverflow.com/questions/45010544/react-cannot-read-property-of-undefined-despite-correct-binding) – Shubham Khatri Aug 02 '17 at 05:30

2 Answers2

4

Use an arrow function so that this is preserved.

this.state.cart.forEach((item, index) => {
    // ...
})
Josiah Keller
  • 3,635
  • 3
  • 23
  • 35
1

You need to bind your functions, to get access to this in functions body:

constructor(props) {
    super(props);
    this.itemBucket = this.itemBucket.bind(this);
    this.countTotal = this.countTotal.bind(this);
    this.state = {items: this.props.cart,cart: [],total: 0};
}
Andrii Starusiev
  • 7,564
  • 2
  • 28
  • 37