feners
feners

Reputation: 675

Problems deleting items from Redux store using onClick event

I want to be able to delete an specific object from an array in my store. I made a delete item function that works and deletes the objects, however I haven't been able to figure out how to make this function work when I use a button that is rendered with each object with map. This is my component:

import React, { Component } from 'react';
import {addCart} from './Shop';
import { removeCart } from '../../actions'; 
import { connect } from 'react-redux';

export class Cart extends Component {
    constructor(props) {
        super(props);
        this.state = {items: this.props.cart,cart: [],total: 0};
    }

    handleClick(item) {
        this.props.onCartRemove(item);
    } 

    ...


    render() {
        return(
            <div className= "Webcart" id="Webcart">
                <div>
                    {this.state.items.map((item, index) => {
                        return <li className='cartItems' key={'cartItems_'+index}>
                            <h4>{item.item}</h4>
                            <p>Size: {item.size}</p>
                            <p>Price: {item.price}</p>
                            <button onClick={this.handleClick}>Remove</button>
                        </li>
})}
                </div>
                <div>Total: ${this.countTotal()}</div>
            </div>
        );
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        onCartAdd: (cart) => {
            dispatch(addCart(cart));
        },
        onCartRemove: (item) => {
            dispatch(removeCart(item));
        },
    }
}

function mapStateToProps(state) {
  return { cart: state.cart };
}

export default connect(mapStateToProps, mapDispatchToProps)(Cart);

With the function handleClick I get Uncaught TypeError: Cannot read property 'props' of null. If I try something like

deleteItem() {
        return this.state.items.reduce((acc, item) => {
            return this.props.onCartRemove(item);
        })
    }

... the code deletes all items in the loop without any errors. How can I can use the button to remove that particular item?

Upvotes: 0

Views: 360

Answers (2)

larv
larv

Reputation: 938

Are you really getting the item for it to be removed?

try this on your button inside your map:

<button onClick={() => this.handleClick(item)}>Remove</button>

Upvotes: 1

Christian Hain
Christian Hain

Reputation: 639

You need to bind your handler.

constructor(props) {
    super(props);
    this.state = {items: this.props.cart,cart: [],total: 0};
    this.handleClick = this.handleClick.bind(this);
}

https://facebook.github.io/react/docs/handling-events.html

Upvotes: 1

Related Questions