File tree Expand file tree Collapse file tree 1 file changed +83
-0
lines changed Expand file tree Collapse file tree 1 file changed +83
-0
lines changed Original file line number Diff line number Diff line change 1+ import { defineStore } from "pinia" ;
2+
3+ const state = {
4+ cart : [ ] ,
5+ order : { } ,
6+ customer : { } ,
7+ loading : true ,
8+ error : null ,
9+ } ;
10+
11+ export const useCart = defineStore ( "shopState" , {
12+ state : ( ) => state ,
13+ actions : {
14+ async getProductsFromApi ( ) {
15+ try {
16+ this . loading = true ;
17+ const response = await axios . get ( "/api/products" ) ;
18+ this . products = response . data ;
19+ this . loading = false ;
20+ } catch ( error ) {
21+ this . error = error ;
22+ }
23+ } ,
24+ addToCart ( { item } ) {
25+ const foundProductInCartIndex = this . cart . findIndex (
26+ ( cartItem ) => item . slug === cartItem . slug
27+ ) ;
28+
29+ if ( foundProductInCartIndex > - 1 ) {
30+ this . cart [ foundProductInCartIndex ] . quantity += 1 ;
31+ } else {
32+ item . quantity = 1 ;
33+ this . cart . push ( item ) ;
34+ }
35+ } ,
36+ removeProductFromCart ( { item } ) {
37+ this . cart . splice ( this . cart . indexOf ( item ) , 1 ) ;
38+ } ,
39+
40+ clearCart ( ) {
41+ this . cart . length = 0 ;
42+ } ,
43+ clearCustomer ( ) {
44+ this . customer = { } ;
45+ } ,
46+ clearOrder ( ) {
47+ this . order = { } ;
48+ } ,
49+ saveCustomerDetails ( customer ) {
50+ this . customer = customer ;
51+ } ,
52+ saveOrderId ( order ) {
53+ this . order = order ;
54+ } ,
55+ getSingleProduct ( slug ) {
56+ return this . products . find ( ( product ) => product . slug === slug ) ;
57+ } ,
58+ } ,
59+ getters : {
60+ getCartQuantity ( ) {
61+ return this . cart . reduce (
62+ ( total , product ) => total + product . quantity ,
63+ 0
64+ ) ;
65+ } ,
66+ getOrderDetails ( ) {
67+ return this . order ;
68+ } ,
69+ getCartContent ( ) {
70+ return this . cart ;
71+ } ,
72+ getCustomerDetails ( ) {
73+ return this . customer ;
74+ } ,
75+ getCartTotal ( ) {
76+ return this . cart . reduce (
77+ ( total , product ) => total + product . price * product . quantity ,
78+ 0
79+ ) ;
80+ } ,
81+ } ,
82+ persist : true ,
83+ } ) ;
You can’t perform that action at this time.
0 commit comments