-
-
Notifications
You must be signed in to change notification settings - Fork 405
/
Copy pathindex.js
92 lines (87 loc) · 2.68 KB
/
index.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import axios from "axios";
import data from "~/static/storedata.json";
export const state = () => ({
cartUIStatus: "idle",
storedata: data,
cart: [],
clientSecret: "" // Required to initiate the payment from the client
});
export const getters = {
featuredProducts: state => state.storedata.slice(0, 3),
women: state => state.storedata.filter(el => el.gender === "Female"),
men: state => state.storedata.filter(el => el.gender === "Male"),
cartCount: state => {
if (!state.cart.length) return 0;
return state.cart.reduce((ac, next) => ac + next.quantity, 0);
},
cartTotal: state => {
if (!state.cart.length) return 0;
return state.cart.reduce((ac, next) => ac + next.quantity * next.price, 0);
},
cartItems: state => {
if (!state.cart.length) return [];
return state.cart.map(item => {
return {
id: item.id,
quantity: item.quantity
};
});
},
clientSecret: state => state.clientSecret
};
export const mutations = {
updateCartUI: (state, payload) => {
state.cartUIStatus = payload;
},
clearCart: state => {
//this clears the cart
(state.cart = []), (state.cartUIStatus = "idle");
},
addToCart: (state, payload) => {
let itemfound = state.cart.find(el => el.id === payload.id);
itemfound
? (itemfound.quantity += payload.quantity)
: state.cart.push(payload)
},
setClientSecret: (state, payload) => {
state.clientSecret = payload;
},
addOneToCart: (state, payload) => {
let itemfound = state.cart.find(el => el.id === payload.id)
itemfound ? itemfound.quantity++ : state.cart.push(payload)
},
removeOneFromCart: (state, payload) => {
let index = state.cart.findIndex(el => el.id === payload.id)
state.cart[index].quantity
? state.cart[index].quantity--
: state.cart.splice(index, 1)
},
removeAllFromCart: (state, payload) => {
state.cart = state.cart.filter(el => el.id !== payload.id)
}
};
export const actions = {
async createPaymentIntent({ getters, commit }) {
try {
// Create a PaymentIntent with the information about the order
const result = await axios.post(
"https://ecommerce-netlify.netlify.app/.netlify/functions/create-payment-intent",
{
items: getters.cartItems
},
{
headers: {
"Content-Type": "application/json"
}
}
);
if (result.data.clientSecret) {
// Store a reference to the client secret created by the PaymentIntent
// This secret will be used to finalize the payment from the client
commit("setClientSecret", result.data.clientSecret);
}
} catch (e) {
console.log("error", e);
}
}
};