aboutsummaryrefslogtreecommitdiff
path: root/client/src/store/index.js
blob: 3d612c7cd9ef7f21a72b37861e7ac4db90cee29c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import {createStore} from 'vuex'
import axios from 'axios';

export default createStore({
  state: {
    products: [],
    cart: []
  },
  getters: {
    getProducts(state) {
      return state.products;
    },
    getCart(state) {
      return state.cart.sort((x, y) => x.name > y.name);
    },
    getCartSize(state) {
      let sum = 0;
      state.cart.forEach(x => sum += x.quantity);
      return sum;
    },
    getCartPrice(state) {
      let sum = 0;
      state.cart.forEach(x => sum += x.price * x.quantity);
      return sum;
    }
  },
  mutations: {
    setProducts(state, products) {
      state.products = products;
    },
    addToCart(state, product) {
      let foundProduct = state.cart.find(x => x.id == product._id);
      if (foundProduct)
        foundProduct.quantity++;
      else
        state.cart.push({
          id: product._id,
          name: product.name,
          price: product.price,
          quantity: 1
        });
    }
  },
  actions: {
    async pullProducts(context) {
      await axios.get(`${process.env.VUE_APP_ROOT_API}/products`)
        .then(response => context.commit('setProducts', response.data))
        .catch(error => console.error(error));
    }
  },
  modules: {
  }
})