I'm trying to save a user's item selection whenever this item selection is added to a cart. I use Redux to pass the item data whenever the user presses add to cart on a particular item. In my Cart component I can view the the item selection data of the last item the was added to cart. This user selection item data looks like Object {price: 25, item: "Hoodie", size: "medium"}. I want to be able to store each selection that is added to the cart in my Cart component. This is Cart:
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() {
var total = 0;
console.log(this.state.cart);
this.state.cart.forEach(function(item, index){
total = total + item.price;
console.log (total);
})
}
componentDidMount () {
window.scrollTo(0, 0);
this.itemBucket();
}
render() {
return(
<div className= "Webcart" id="Webcart">
<addCart cartItem={this.props.cart} />
</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
onCartAdd: (cart) => {
dispatch(addCart(cart));
},
}
}
function mapStateToProps(state) {
return { cart: state.cart };
}
export default connect(mapStateToProps, mapDispatchToProps)(Cart);
I've set up itemBucket() as a function to add each item selection to a cart array found in the state. However this does not work and only the last item added to the cart is passed. This may have to do with changing how my Redux Store is working, but I don't really know how to apply this. This is my Redux Store:
import { createStore, applyMiddleware } from 'redux';
import reducer from './reducers';
import thunkMiddleware from 'redux-thunk';
import {createLogger} from 'redux-logger';
const store = createStore(
reducer,
applyMiddleware(
createLogger(),
thunkMiddleware
)
);
export default store;
How can I save each item that is passed to Cart even when the page is refreshed or changed?
EDIT
Here is my reducer component:
import {ADD_CART} from './actions';
export default Reducer;
var initialState = {
cart:{},
data: [],
url: "/api/comments",
pollInterval: 2000
};
function Reducer(state = initialState, action){
switch(action.type){
case ADD_CART:
return {
...state,
cart: action.payload
}
default:
return state
};
}