All files / src/redux/features wishlistSlice.ts

67.57% Statements 148/219
73.07% Branches 19/26
100% Functions 4/4
67.57% Lines 148/219

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 2201x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                           1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x                       8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x     2x 2x 2x     2x 1x 1x 1x 1x 1x 1x                           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 34x 34x     34x 34x 32x 32x 1x 1x 1x 14x 14x       14x 1x 1x 36x 36x 1x 1x 36x 36x 1x 1x 1x 36x 36x 1x 1x 1x 36x 36x 36x 36x 9x 36x 36x   36x 36x 9x 9x 9x 36x 36x 36x 36x 3x 36x 36x 1x 36x 36x 36x 36x 2x 36x 36x 1x 36x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
 
type InitialState = {
  items: WishListItem[];
  isLoaded: boolean;
  loading: boolean;
  error: string | null;
};
 
export type WishListItem = {
  id: number;
  title: string;
  price: number;
  discountedPrice: number;
  quantity: number;
  status?: string;
  imgs?: {
    thumbnails: string[];
    previews: string[];
  };
};
 
const initialState: InitialState = {
  items: [],
  isLoaded: false,
  loading: false,
  error: null};
 
// Async thunk to fetch wishlist from API
export const fetchWishlist = createAsyncThunk(
  "wishlist/fetchWishlist",
  async (_, { rejectWithValue }) => {
    try {
      const response = await fetch("/api/wishlist");
      if (response.status === 401) {
        // User not authenticated - return empty array, not an error
        return [];
      }
      if (!response.ok) {
        throw new Error("Failed to fetch wishlist");
      }
      const result = await response.json();
      // Handle API response format: { success: true, data: [...] }
      const data = result?.data ?? result;

      // Ensure data is an array
      if (!Array.isArray(data)) {
        return [];
      }

      // Transform API response to match WishListItem type
      return data.map((item: {
        id: number;
        title: string;
        price: number;
        discountedPrice: number;
        imgs?: { thumbnails: string[]; previews: string[] };
      }) => ({
        id: item.id,
        title: item.title,
        price: item.price,
        discountedPrice: item.discountedPrice,
        quantity: 1,
        status: "in_stock",
        imgs: item.imgs}));
    } catch (error) {
      return rejectWithValue(error instanceof Error ? error.message : "Failed to fetch wishlist");
    }
  }
);
 
// Async thunk to add item to wishlist
export const addToWishlistAsync = createAsyncThunk(
  "wishlist/addToWishlist",
  async (productId: number, { rejectWithValue }) => {
    try {
      const response = await fetch("/api/wishlist", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ productId })});

      if (response.status === 401) {
        return rejectWithValue("LOGIN_REQUIRED");
      }

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Failed to add to wishlist");
      }

      return productId;
    } catch (error) {
      return rejectWithValue(error instanceof Error ? error.message : "Failed to add to wishlist");
    }
  }
);
 
// Async thunk to remove item from wishlist
export const removeFromWishlistAsync = createAsyncThunk(
  "wishlist/removeFromWishlist",
  async (productId: number, { rejectWithValue }) => {
    try {
      const response = await fetch(`/api/wishlist/${productId}`, {
        method: "DELETE"});
 
      if (!response.ok) {
        throw new Error("Failed to remove from wishlist");
      }
 
      return productId;
    } catch (error) {
      return rejectWithValue(error instanceof Error ? error.message : "Failed to remove from wishlist");
    }
  }
);
 
// Async thunk to clear all wishlist items
export const clearWishlistAsync = createAsyncThunk(
  "wishlist/clearWishlist",
  async (_, { rejectWithValue }) => {
    try {
      const response = await fetch("/api/wishlist", {
        method: "DELETE"});

      if (!response.ok) {
        throw new Error("Failed to clear wishlist");
      }

      return true;
    } catch (error) {
      return rejectWithValue(error instanceof Error ? error.message : "Failed to clear wishlist");
    }
  }
);
 
export const wishlist = createSlice({
  name: "wishlist",
  initialState,
  reducers: {
    clearWishlistError: (state) => {
      state.error = null;
    },
    // Optimistically add item to local state (used before API call completes)
    addItemToWishlistOptimistic: (state, action: PayloadAction<WishListItem>) => {
      // Ensure items is an array
      if (!Array.isArray(state.items)) {
        state.items = [];
      }
      const existingItem = state.items.find((item) => item.id === action.payload.id);
      if (!existingItem) {
        state.items.push(action.payload);
      }
    },
    // Remove item from local state (used for optimistic updates)
    removeItemFromWishlistOptimistic: (state, action: PayloadAction<number>) => {
      // Ensure items is an array
      if (!Array.isArray(state.items)) {
        state.items = [];
        return;
      }
      state.items = state.items.filter((item) => item.id !== action.payload);
    }},
  extraReducers: (builder) => {
    // Fetch wishlist
    builder.addCase(fetchWishlist.pending, (state) => {
      state.loading = true;
      state.error = null;
    });
    builder.addCase(fetchWishlist.fulfilled, (state, action) => {
      state.loading = false;
      state.items = Array.isArray(action.payload) ? action.payload : [];
      state.isLoaded = true;
    });
    builder.addCase(fetchWishlist.rejected, (state, action) => {
      state.loading = false;
      state.error = action.payload as string;
      state.isLoaded = true;
    });
 
    // Add to wishlist
    builder.addCase(addToWishlistAsync.pending, (state) => {
      state.error = null;
    });
    builder.addCase(addToWishlistAsync.fulfilled, () => {
      // Item already added optimistically
    });
    builder.addCase(addToWishlistAsync.rejected, (state, action) => {
      state.error = action.payload as string;
      // If failed, we should remove the optimistically added item
      // This is handled in the component
    });
 
    // Remove from wishlist
    builder.addCase(removeFromWishlistAsync.fulfilled, (state, action) => {
      state.items = state.items.filter((item) => item.id !== action.payload);
    });
    builder.addCase(removeFromWishlistAsync.rejected, (state, action) => {
      state.error = action.payload as string;
    });
 
    // Clear wishlist
    builder.addCase(clearWishlistAsync.fulfilled, (state) => {
      state.items = [];
    });
    builder.addCase(clearWishlistAsync.rejected, (state, action) => {
      state.error = action.payload as string;
    });
  }});
 
export const {
  clearWishlistError,
  addItemToWishlistOptimistic,
  removeItemFromWishlistOptimistic} = wishlist.actions;
 
// Legacy exports for backward compatibility (deprecated - use async versions)
export const addItemToWishlist = addItemToWishlistOptimistic;
export const removeItemFromWishlist = removeItemFromWishlistOptimistic;
 
export default wishlist.reducer;