Reputation: 77
I am simply trying to call AddToCart on each item in the list when the onclick handler is triggered, which simply decreases the item's quantity by 1 unit. Here is the relevant code:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { AddToCart } from '../actions/add_to_cart';
class ItemList extends Component {
render() {
return (
<div>
<ol>
{this.props.itemList.map((item) =>
<li key={item.id} >
name: {item.name} ||
price: ${item.price} ||
Quantity: {item.quantity}
<button
onClick={() => this.props.AddToCart(item.id)}
>Add To Cart
</button>
</li>
)}
</ol>
</div>
);
}
}
function mapDispatchToProps (dispatch) {
return bindActionCreators({ AddToCart }, dispatch);
}
function mapStateToProps(state) {
return { itemList: state.itemList }
}
export default connect(mapStateToProps,mapDispatchToProps)(ItemList);
This is the Action Creator:
export const ADD_TO_CART = 'ADD_TO_CART';
export function addToCart(id) {
return {
type: ADD_TO_CART,
id
};
}
This is the reducer:
import { ADD_TO_LIST } from '../actions/add_to_list';
import { ADD_TO_CART } from '../actions/add_to_cart';
export default function (state = [], action) {
console.log('action recieved', action);
switch (action.type) {
case ADD_TO_LIST:
console.log(state)
return [
...state,
{ id: action.id, name: action.name, price: action.price, quantity: 10 }
]
case ADD_TO_CART:
return state.map((item) => {
if(item.id === action.id){
// return {...state, quantity: 0}
return Object.assign({}, item, {quantity: item.quantity - 1})
}
return item
})
}
return state;
console.log(state);
}
Been stuck on this for longer than I'de like to share. Any HELP PLEASE!!
Upvotes: 0
Views: 864
Reputation: 17638
You are importing AddToCart:
import { AddToCart } from '../actions/add_to_cart';
but your function's name is addToCart in you action creator. It must be:
import { addToCart } from '../actions/add_to_cart';
Upvotes: 3