I am trying to create a cash register system. Now I want to create an order list, which contains products and how many of each I sold. I am using redux store here.
My problem is when I use the ADDORDERITEM case, it receives an action.order like {id: 1, name:"halve zolen", categoryId:1, price: 1.0} for example. In the case statement, the numberOfOrderItems gets set to what number is at that moment in the state.numberOfOrderItems. This works for one item, but if I add the same item with a different amount, I end up with an array with 2 objects with the amount that was last entered, while this should be 2 different amounts here. If I check action.order after I set the numberOfOrderItems it is a correct order, so what is going wrong here? My guess it has something to do with me using state.numberOfOrderItems here which make a subscription to that, and updates it whenever this variable is used somewhere. Is there some way to just take a snapshot of it and never update it again?
My code: Store.js:
import {createStore} from 'redux';
const kassaReducer = (state = {orders: [], numberOfOrderItems: ""}, action) => {
switch (action.type){
case "ADDORDERITEM":
let newOrder = action.order;
newOrder.numberOfOrderItems = state.numberOfOrderItems;
return {orders: [...state.orders, newOrder], numberOfOrderItems: ""};
case "REMOVEORDERITEM":
return {orders : state.orders.remove(state.orders.indexOf(action.order)), numberOfOrderItems: state.numberOfOrderItems};
case "SETITEMNUMBER":
return {orders : state.orders, numberOfOrderItems: state.numberOfOrderItems === "" ? action.numberOfOrderItems : (state.numberOfOrderItems action.numberOfOrderItems)};
}
return state;
}
const store = createStore(kassaReducer);
export default store;
CodePudding user response:
Edit: Ok I read your post one more time
This still is invalid and is causing problems:
action.order.numberOfOrderItems = state.numberOfOrderItems;
but it should be:
case "ADDORDERITEM":
return {orders: [...state.orders, action.order], numberOfOrderItems: state.numberOfOrderItems action.numberOfOrderItems };