cartStore.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { action, makeObservable, observable, computed } from 'mobx';
  2. class CartStore {
  3. constructor() {
  4. makeObservable(this, {
  5. items: observable,
  6. isOpen: observable,
  7. addProduct: action,
  8. substractProduct: action,
  9. removeProduct: action,
  10. setIsOpen: action,
  11. count: computed,
  12. total: computed,
  13. });
  14. }
  15. items = [];
  16. isOpen = false;
  17. get count() {
  18. return this.items.reduce((accumulator, item) => accumulator + item.quantity, 0);
  19. }
  20. get total() {
  21. return this.items.reduce((accumulator, item) => accumulator + (item.quantity * item.product.price), 0);
  22. }
  23. addProduct(product) {
  24. const index = this.items.findIndex(item => product._id === item.product._id);
  25. if (index !== -1) {
  26. this.items[index].quantity ++;
  27. } else {
  28. this.items = this.items.concat({product, quantity: 1});
  29. }
  30. }
  31. substractProduct(product) {
  32. const index = this.items.findIndex(item => product._id === item.product._id);
  33. if (index === -1) {
  34. return;
  35. }
  36. if (this.items[index].quantity > 1) {
  37. this.items[index].quantity--;
  38. } else {
  39. this.removeProduct(product);
  40. }
  41. }
  42. removeProduct(product) {
  43. this.items = this.items.filter(item => product._id !== item.product._id);
  44. }
  45. setIsOpen(state) {
  46. this.isOpen = state;
  47. }
  48. }
  49. export default new CartStore();