11import { createAsyncThunk , createSlice } from "@reduxjs/toolkit" ;
2- import { addToCart , fetchItemsByUserId , updateCart } from "./cartAPI" ;
2+ import {
3+ addToCart ,
4+ fetchItemsByUserId ,
5+ updateCart ,
6+ deleteItemFromCart ,
7+ } from "./cartAPI" ;
38
49const initialState = {
510 items : [ ] ,
@@ -24,8 +29,16 @@ export const fetchItemsByUserIdAsync = createAsyncThunk(
2429) ;
2530export const updateCartAsync = createAsyncThunk (
2631 "cart/updateCart" ,
27- async ( item ) => {
28- const response = await updateCart ( item ) ;
32+ async ( update ) => {
33+ const response = await updateCart ( update ) ;
34+ // The value we return becomes the `fulfilled` action payload
35+ return response . data ;
36+ }
37+ ) ;
38+ export const deleteItemFromCartAsync = createAsyncThunk (
39+ "cart/deleteItemFromCart" ,
40+ async ( itemId ) => {
41+ const response = await deleteItemFromCart ( itemId ) ;
2942 // The value we return becomes the `fulfilled` action payload
3043 return response . data ;
3144 }
@@ -64,6 +77,16 @@ export const cartSlice = createSlice({
6477 ( item ) => item . id === action . payload . id
6578 ) ;
6679 state . items [ index ] = action . payload ;
80+ } )
81+ . addCase ( deleteItemFromCartAsync . pending , ( state ) => {
82+ state . status = "loading" ;
83+ } )
84+ . addCase ( deleteItemFromCartAsync . fulfilled , ( state , action ) => {
85+ state . status = "idle" ;
86+ const index = state . items . findIndex (
87+ ( item ) => item . id === action . payload . id
88+ ) ;
89+ state . items . splice ( index , 1 ) ;
6790 } ) ;
6891 } ,
6992} ) ;
0 commit comments