@@ -2,6 +2,8 @@ import {createSlice, PayloadAction} from '@reduxjs/toolkit';
2
2
import { RootState } from 'store/store' ;
3
3
import { Product } from "models/Product" ;
4
4
import { CartItem } from "models/CartItem" ;
5
+ import API_PATHS from "../constants/apiPaths" ;
6
+ import axios from 'axios' ;
5
7
6
8
interface CartState {
7
9
items : CartItem [ ]
@@ -15,6 +17,13 @@ export const cartSlice = createSlice({
15
17
name : 'cart' ,
16
18
initialState,
17
19
reducers : {
20
+ updateFromApi : ( state , { payload : { items } } : PayloadAction < CartState > ) => {
21
+ return {
22
+ items : [
23
+ ...items ,
24
+ ] ,
25
+ }
26
+ } ,
18
27
// Use the PayloadAction type to declare the contents of `action.payload`
19
28
addToCart : ( state , action : PayloadAction < Product > ) => {
20
29
const { items} = state ;
@@ -44,7 +53,37 @@ export const cartSlice = createSlice({
44
53
} ,
45
54
} ) ;
46
55
47
- export const { addToCart, removeFromCart, clearCart} = cartSlice . actions ;
56
+ export const addToCart = ( product : Product ) => async ( dispatch : any , getState : any ) => {
57
+ dispatch ( cartSlice . actions . addToCart ( product ) ) ;
58
+ const { cart : { items } } = getState ( ) ;
59
+ await axios . put ( `${ API_PATHS . cart } /profile/cart` , { items } , {
60
+ headers : {
61
+ Authorization : `Basic ${ localStorage . getItem ( 'authorization_token' ) } ` ,
62
+ } ,
63
+ } )
64
+ } ;
65
+
66
+ export const removeFromCart = ( product : Product ) => async ( dispatch : any , getState : any ) => {
67
+ dispatch ( cartSlice . actions . removeFromCart ( product ) ) ;
68
+ const { cart : { items } } = getState ( ) ;
69
+ await axios . put ( `${ API_PATHS . cart } /profile/cart` , { items } , {
70
+ headers : {
71
+ Authorization : `Basic ${ localStorage . getItem ( 'authorization_token' ) } ` ,
72
+ } ,
73
+ } )
74
+ } ;
75
+
76
+ export const clearCart = ( ) => async ( dispatch : any , getState : any ) => {
77
+ dispatch ( cartSlice . actions . clearCart ( ) ) ;
78
+ const { cart : { items } } = getState ( ) ;
79
+ await axios . put ( `${ API_PATHS . cart } /profile/cart` , { items } , {
80
+ headers : {
81
+ Authorization : `Basic ${ localStorage . getItem ( 'authorization_token' ) } ` ,
82
+ } ,
83
+ } )
84
+ } ;
85
+
86
+ export const { updateFromApi} = cartSlice . actions ;
48
87
49
88
50
89
// The function below is called a selector and allows us to select a value from
0 commit comments