cartReducer.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. function cartReducer (state = {}, { type, good = {}, count = 1 }) {
  2. const types = {
  3. CART_ADD () {
  4. const { _id } = good;
  5. return {
  6. ...state,
  7. [_id]: { good, count: count + (state[_id]?.count || 0) }
  8. };
  9. },
  10. CART_MINUS () {
  11. const { _id } = good;
  12. return {
  13. ...state,
  14. [_id]: { good, count: (-count + (state[_id]?.count || 0)) < 1 ? 0 : -count + (state[_id]?.count || 0) }
  15. };
  16. },
  17. CART_REMOVE () {
  18. const { _id } = good;
  19. const newState = { ...state };
  20. const arrKeys = Object.keys(newState);
  21. for (const key of arrKeys) {
  22. if (_id === key) {
  23. delete newState[_id];
  24. }
  25. }
  26. return {
  27. ...newState
  28. };
  29. },
  30. CART_CHANGE () {
  31. const { _id } = good;
  32. return {
  33. ...state,
  34. [_id]: { good, count }
  35. };
  36. },
  37. CART_CLEAR () {
  38. return {
  39. };
  40. },
  41. AUTH_LOGOUT () {
  42. localStorage.clear();
  43. return {};
  44. }
  45. };
  46. if (type in types) { return types[type](); };
  47. return state;
  48. }
  49. export default cartReducer;