@@ -2,6 +2,8 @@ import {createSlice, PayloadAction} from '@reduxjs/toolkit';
22import { RootState } from 'store/store' ;
33import { Product } from "models/Product" ;
44import { CartItem } from "models/CartItem" ;
5+ import API_PATHS from "../constants/apiPaths" ;
6+ import axios from 'axios' ;
57
68interface CartState {
79 items : CartItem [ ]
@@ -15,6 +17,13 @@ export const cartSlice = createSlice({
1517 name : 'cart' ,
1618 initialState,
1719 reducers : {
20+ updateFromApi : ( state , { payload : { items } } : PayloadAction < CartState > ) => {
21+ return {
22+ items : [
23+ ...items ,
24+ ] ,
25+ }
26+ } ,
1827 // Use the PayloadAction type to declare the contents of `action.payload`
1928 addToCart : ( state , action : PayloadAction < Product > ) => {
2029 const { items} = state ;
@@ -44,7 +53,37 @@ export const cartSlice = createSlice({
4453 } ,
4554} ) ;
4655
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 ;
4887
4988
5089// The function below is called a selector and allows us to select a value from
0 commit comments