I am learning react. I was trying to understand redux. I developed a simple page which adds a items in shopping bag. Now i am trying to implement removing items.
My goal is to pass an index in REMOVE_ITEM action. I will remove the item with that index in my action. But whenever i click remove Button it gives me the following error.
TypeError: Cannot read property 'index' of undefined
this error is from the line:
onClick={() =>this.props.REMOVE_ITEM({ index: this.props.items[i].index})
I tried to use array.map function first. but inside array.map this.props was outside the variable scope. So i moved the code in a separate function. Then called that function from render. But still my problem was not solved.
I also tried to bind this.props.REMOVE_ITEM in constructor. But i was not successful in doing so.
My entire code is given below.
import React, { Component } from "react";
import { connect } from "react-redux";
class ShopingBag extends Component {
constructor(props) {
super(props);
this.state = {};
}
bag_items() {
var list = [];
console.log(this.props);
for (var i = 0; i < this.props.items.length; i++) {
list.push(
<tr>
<td>{this.props.items[i].index}</td>
<td>{this.props.items[i].name}</td>
<td>{this.props.items[i].unit}</td>
<td>
<button
onClick={() =>
this.props.REMOVE_ITEM({
index: this.props.items[i].index
})
}
>
Remove
</button>
</td>
</tr>
);
}
return list;
}
render() {
console.log(this.props);
return (
<div>
Shoping Bag
<div>
<table>
<thead>
<tr>
<th>id</th>
<th>item</th>
<th>unit</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{/* {this.props.items.map(function(item, i) {
return (
<tr key={i}>
<td>{item.index}</td>
<td>{item.name}</td>
<td>{item.unit}</td>
<td>
<button
onClick={() => this.props.REMOVE_ITEM({ index: 0 })}
>
Remove
</button>
</td>
</tr>
);
})} */}
{this.bag_items()}
<tr>
<td />
<td />
<td />
<td>{this.props.total}</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return {
REMOVE_ITEM: data => dispatch({ type: "REMOVE_ITEM", payload: data })
};
};
const mapStateToProps = store => {
return {
items: store.sR.items,
total: store.sR.total
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ShopingBag);