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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | 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 1x 1x 1x 1x 1x 1x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 365x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 177x 177x 177x 177x 177x 177x 177x 177x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 9x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 7x 7x 7x 7x 177x 177x 177x 177x 177x 177x 177x 4x 4x 4x 4x 177x 177x 177x 177x 177x 177x 177x 3x 3x 3x 3x 3x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 23x 11x 11x 11x 11x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 11x 11x 11x 11x 11x 2x 2x 2x 2x 2x 2x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 2x 2x 11x 11x 11x 2x 2x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x | 'use client';
import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useSession } from 'next-auth/react';
import { AppDispatch, RootState } from '@/redux/store';
import { updateQuickView } from '@/redux/features/quickViewSlice';
import { addItemToCart } from '@/redux/features/cartSlice';
import { addToCartAsync } from '@/redux/features/cartSliceApi';
import { addToWishlistAsync, removeFromWishlistAsync, addItemToWishlistOptimistic, removeItemFromWishlistOptimistic } from '@/redux/features/wishlistSlice';
import { updateProductDetails } from '@/redux/features/productDetails';
import { useModalContext } from '@/contexts';
import { eventTracking } from '@/lib/event-tracking';
import { useToast } from '@/hooks/useToast';
import { Product } from '@/types/product';
import { clientLogger } from '@/lib/logging/clientLogger';
import { useFunnelSteps } from '@/hooks/useFunnelTracking';
/**
* useProductActions Hook
*
* Centralized hook for common product actions (add to cart, wishlist, quick view, etc.)
* Provides consistent behavior across all product components with built-in:
* - Redux state updates
* - Event tracking
* - Toast notifications
* - Error handling
*
* @example
* ```tsx
* const ProductCard = ({ product }) => {
* const { addToCart, addToWishlist, showQuickView } = useProductActions(product);
*
* return (
* <div>
* <button onClick={() => addToCart()}>Add to Cart</button>
* <button onClick={addToWishlist}>Add to Wishlist</button>
* <button onClick={showQuickView}>Quick View</button>
* </div>
* );
* };
* ```
*/
export function useProductActions(product: Product) {
const dispatch = useDispatch<AppDispatch>();
const { openModal } = useModalContext();
const { addToast } = useToast();
const { trackStep } = useFunnelSteps();
const { status } = useSession();
const isAuthenticated = status === 'authenticated';
// Check if product is in wishlist
const isInWishlist = useSelector((state: RootState) =>
state.wishlistReducer.items.some((item) => item.id === product.id)
);
/**
* Add product to cart
* @param quantity - Number of items to add (default: 1)
*
* When authenticated: saves to database via API AND updates local Redux state
* When not authenticated: saves to Redux + cookie
*/
const addToCart = useCallback(
async (quantity: number = 1) => {
try {
// Always update local Redux state immediately for instant UI feedback
dispatch(
addItemToCart({
...product,
quantity})
);
// If authenticated, also persist to database
if (isAuthenticated) {
try {
await dispatch(addToCartAsync({ productId: product.id, quantity }));
} catch (apiError) {
// API failed but local state is already updated
// Log error but don't show to user since local cart works
clientLogger.warn('Failed to sync cart to database, will retry on next action', { error: apiError instanceof Error ? apiError.message : String(apiError) });
}
}
// Track event (legacy)
eventTracking.addToCart(product.id, product.title, product.discountedPrice);
// Track funnel step for analytics
trackStep('checkout', 'add_to_cart', {
product_id: product.id,
product_name: product.title,
price: product.discountedPrice,
quantity});
// Show success toast
addToast({
message: `${product.title} added to cart`,
variant: 'success',
duration: 3000});
} catch (error) {
clientLogger.error('Error adding to cart', error instanceof Error ? error : new Error(String(error)));
addToast({
message: 'Failed to add item to cart',
variant: 'error',
duration: 3000});
}
},
[product, dispatch, addToast, trackStep, isAuthenticated]
);
/**
* Add product to wishlist
*/
const addToWishlist = useCallback(async () => {
// Optimistically add to local state
dispatch(
addItemToWishlistOptimistic({
...product,
status: 'in_stock',
quantity: 1})
);
// Track event
eventTracking.addToWishlist(product.id, product.title);
// Show success toast immediately (optimistic)
addToast({
message: `${product.title} added to wishlist`,
variant: 'success',
duration: 3000});
try {
// Call API to persist to database
const result = await dispatch(addToWishlistAsync(product.id));
if (addToWishlistAsync.rejected.match(result)) {
// API call failed - check if login required
if (result.payload === 'LOGIN_REQUIRED') {
// Remove from local state since user isn't logged in
dispatch(removeItemFromWishlistOptimistic(product.id));
addToast({
message: 'Please sign in to save your wishlist',
variant: 'warning',
duration: 4000});
} else {
// Other error - remove from local state
dispatch(removeItemFromWishlistOptimistic(product.id));
addToast({
message: 'Failed to save to wishlist',
variant: 'error',
duration: 3000});
}
}
} catch (error) {
clientLogger.error('Error adding to wishlist', error instanceof Error ? error : new Error(String(error)));
// Remove optimistically added item on error
dispatch(removeItemFromWishlistOptimistic(product.id));
addToast({
message: 'Failed to add item to wishlist',
variant: 'error',
duration: 3000});
}
}, [product, dispatch, addToast]);
/**
* Remove product from wishlist
*/
const removeFromWishlist = useCallback(async () => {
// Optimistically remove from local state
dispatch(removeItemFromWishlistOptimistic(product.id));
// Show success toast immediately (optimistic)
addToast({
message: `${product.title} removed from wishlist`,
variant: 'success',
duration: 3000});
try {
// Call API to remove from database
const result = await dispatch(removeFromWishlistAsync(product.id));
if (removeFromWishlistAsync.rejected.match(result)) {
// API call failed - re-add to local state
dispatch(
addItemToWishlistOptimistic({
...product,
status: 'in_stock',
quantity: 1})
);
addToast({
message: 'Failed to remove from wishlist',
variant: 'error',
duration: 3000});
}
} catch (error) {
clientLogger.error('Error removing from wishlist', error instanceof Error ? error : new Error(String(error)));
// Re-add optimistically removed item on error
dispatch(
addItemToWishlistOptimistic({
...product,
status: 'in_stock',
quantity: 1})
);
addToast({
message: 'Failed to remove from wishlist',
variant: 'error',
duration: 3000});
}
}, [product, dispatch, addToast]);
/**
* Toggle product in wishlist (add if not in, remove if in)
*/
const toggleWishlist = useCallback(async () => {
if (isInWishlist) {
await removeFromWishlist();
} else {
await addToWishlist();
}
}, [isInWishlist, addToWishlist, removeFromWishlist]);
/**
* Show quick view modal for product
*/
const showQuickView = useCallback(() => {
try {
dispatch(updateQuickView({ ...product }));
openModal(product.id);
} catch (error) {
clientLogger.error('Error opening quick view', error instanceof Error ? error : new Error(String(error)));
addToast({
message: 'Failed to open quick view',
variant: 'error',
duration: 3000});
}
}, [product, dispatch, openModal, addToast]);
/**
* Navigate to product details page
* Updates Redux state for product details
*/
const viewDetails = useCallback(() => {
try {
dispatch(updateProductDetails({ ...product }));
eventTracking.productView(product.id, product.title);
} catch (error) {
clientLogger.error('Error viewing product details', error instanceof Error ? error : new Error(String(error)));
}
}, [product, dispatch]);
/**
* Add product to comparison list
* (Future feature - placeholder)
*/
const addToCompare = useCallback(() => {
// TODO: Implement comparison feature
addToast({
message: 'Comparison feature coming soon',
variant: 'info',
duration: 3000});
}, [addToast]);
return {
addToCart,
addToWishlist,
removeFromWishlist,
toggleWishlist,
isInWishlist,
showQuickView,
viewDetails,
addToCompare};
}
/**
* Variant hook that doesn't require toast notifications
* Useful for components that handle their own UI feedback
*/
export function useProductActionsWithoutToast(product: Product) {
const dispatch = useDispatch<AppDispatch>();
const { openModal } = useModalContext();
const { trackStep } = useFunnelSteps();
const { status } = useSession();
const isAuthenticated = status === 'authenticated';
// Check if product is in wishlist
const isInWishlist = useSelector((state: RootState) =>
state.wishlistReducer.items.some((item) => item.id === product.id)
);
const addToCart = useCallback(
async (quantity: number = 1) => {
// Always update local Redux state immediately for instant UI feedback
dispatch(addItemToCart({ ...product, quantity }));
// If authenticated, also persist to database
if (isAuthenticated) {
try {
await dispatch(addToCartAsync({ productId: product.id, quantity }));
} catch (error) {
// Log but don't fail - local state is already updated
clientLogger.warn('Failed to sync cart to database', { error: error instanceof Error ? error.message : String(error) });
}
}
eventTracking.addToCart(product.id, product.title, product.discountedPrice);
trackStep('checkout', 'add_to_cart', {
product_id: product.id,
product_name: product.title,
price: product.discountedPrice,
quantity});
},
[product, dispatch, trackStep, isAuthenticated]
);
const addToWishlist = useCallback(async () => {
dispatch(addItemToWishlistOptimistic({ ...product, status: 'in_stock', quantity: 1 }));
eventTracking.addToWishlist(product.id, product.title);
// Call API to persist to database
const result = await dispatch(addToWishlistAsync(product.id));
if (addToWishlistAsync.rejected.match(result)) {
// Remove optimistically added item on failure
dispatch(removeItemFromWishlistOptimistic(product.id));
}
}, [product, dispatch]);
const removeFromWishlist = useCallback(async () => {
dispatch(removeItemFromWishlistOptimistic(product.id));
// Call API to remove from database
const result = await dispatch(removeFromWishlistAsync(product.id));
if (removeFromWishlistAsync.rejected.match(result)) {
// Re-add optimistically removed item on failure
dispatch(addItemToWishlistOptimistic({ ...product, status: 'in_stock', quantity: 1 }));
}
}, [product, dispatch]);
const toggleWishlist = useCallback(async () => {
if (isInWishlist) {
await removeFromWishlist();
} else {
await addToWishlist();
}
}, [isInWishlist, addToWishlist, removeFromWishlist]);
const showQuickView = useCallback(() => {
dispatch(updateQuickView({ ...product }));
openModal(product.id);
}, [product, dispatch, openModal]);
const viewDetails = useCallback(() => {
dispatch(updateProductDetails({ ...product }));
eventTracking.productView(product.id, product.title);
}, [product, dispatch]);
return {
addToCart,
addToWishlist,
removeFromWishlist,
toggleWishlist,
isInWishlist,
showQuickView,
viewDetails};
}
|