mirgate the new api to the wishlist cart... it uses token barer instead of cors credenintals.
'use client'
import Image from "next/image";
import React, { useState, useEffect, useOptimistic } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { CircleArrowLeft, X } from "lucide-react";
import ShoppingBag from "@/components/ShoppingBag";
import Loading from "@/components/Loading";
const handleRemoveItem = async (id) => {
// Optimistically remove the item from the UI
const updatedItems = optimisticWishlist.filter(item => item.id !== id);
addOptimisticWishlistItem(updatedItems);
code
try {
const response = await fetch(`${process.env.NEXT_PUBLIC_API}/wishlist/${id}`, {
method: 'DELETE',
credentials: "include"
});
if (!response.ok) {
throw new Error('Failed to delete item from wishlist');
}
// Update the actual state after successful deletion
setWishlistItems(updatedItems);
} catch (error) {
console.error('Error removing item from wishlist:', error);
// Revert the optimistic update if the server request fails
await fetchWishlist();
}
// Add a product to the user's wishlist
export const addToWishlist = async (req: Request, res: Response) => {
const userId = req.user?.userId;
const { product_id } = req.body;
if (!userId) {
return res.status(400).json({ message: 'User ID not found in token' });
}
if (!product_id) {
return res.status(400).json({ message: 'Product ID is required' });
}
try {
const query = INSERT INTO wishlist (user_id, product_id) VALUES ($1, $2) ON CONFLICT (user_id, product_id) DO NOTHING ;
await pool.query(query, [userId, product_id]);
code
res.status(201).json({ message: 'Product added to wishlist' });
} catch (error) {
console.error('Error adding to wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
// Remove a product from the user's wishlist
export const removeFromWishlist = async (req: Request, res: Response) => {
const userId = req.user?.userId;
const { product_id } = req.body;
if (!userId) {
return res.status(400).json({ message: 'User ID not found in token' });
}
if (!product_id) {
return res.status(400).json({ message: 'Product ID is required' });
}
try {
const query = DELETE FROM wishlist WHERE user_id = $1 AND product_id = $2 ;
const result = await pool.query(query, [userId, product_id]);
code
if (result.rowCount === 0) {
return res.status(404).json({ message: 'Product not found in wishlist' });
}
res.status(200).json({ message: 'Product removed from wishlist' });
} catch (error) {
console.error('Error removing from wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
example of using the api:
'use client';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { usePathname } from 'next/navigation';
import { useInView } from 'react-intersection-observer';
import dynamic from 'next/dynamic';
import ProductItem from './ProductItem';
import ProductLoading from '@/components/ProductLoading';
import NoProductsFound from '@/components/NoProductsFound';
import ProductDetail from '@/components/ProductDetail';
import {NotificationProvider, useNotification} from '@/components/NotificationContext';
const pathname = usePathname(); // Import and use usePathname
const fetchProducts = useCallback(async (currentPage, searchQuery) => { // Added searchQuery
setLoading(true);
setError(null);
try {
await fetchWishlist()
const params = new URLSearchParams({
page: currentPage,
itemsPerPage: 15, // Can be adjusted or made dynamic
});
code
if (c) params.append('c', c);
if (sc) params.append('sc', sc);
if (b) params.append('b', b);
if (sortBy) params.append("sortBy", sortBy);
if (searchQuery) params.append('search', searchQuery); // Use searchQuery
if (minPrice) params.append('minPrice', minPrice);
if (maxPrice && maxPrice !== Infinity) params.append('maxPrice', maxPrice);
if (filter) params.append('filter', filter); // Ensure filter is appended correctly
const response = await fetch(`${process.env.NEXT_PUBLIC_API}/products?${params.toString()}&${filter}`);
if (!response.ok) {
throw new Error('Failed to fetch products');
}
const data = await response.json();
setProducts((prev) => [...prev, ...data.products]);
setHasMore(data.hasMore);
setPage((prev) => prev + 1);
// After the initial fetch, set first.current to false
if (first.current) {
first.current = false;
}
} catch (err) {
console.error('Error fetching products:', err);
setError(err.message || 'An error occurred');
} finally {
setLoading(false);
}
}, [c, sc, b, minPrice, maxPrice, filter]);
// Initial fetch on mount
useEffect(() => {
fetchProducts(page, query); // Pass current query
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // Only run on mount
// Fetch more products when in view
useEffect(() => {
if (inView && hasMore && !loading) {
fetchProducts(page, query); // Pass current query
}
}, [inView, hasMore, loading, fetchProducts, page, query]);
I want you to display the name of the product and its price... use getCheapestPrice function to do so...
Keep the design as it is... make it more smooth and stable and compatiable especially for Safari users.
To migrate your API integration from using CORS credentials to Bearer tokens and enhance the Wishlist component by displaying product names and their cheapest prices, follow the steps below. Additionally, we'll ensure the design remains smooth, stable, and compatible, especially for Safari users.
Backend Adjustments (Optional but Recommended)
Before diving into the frontend changes, it's beneficial to ensure that your backend /wishlist endpoint provides comprehensive product details. This modification will simplify data handling on the frontend.
if (!userId) {
return res.status(400).json({ message: 'User ID not found in token' });
}
try {
const query = `
SELECT p.id
FROM wishlist w
JOIN products p ON w.product_id = p.id
WHERE w.user_id = $1
`;
const { rows } = await pool.query(query, [userId]);
res.status(200).json({ wishlist: rows });
} catch (error) {
console.error('Error fetching wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
Enhanced getWishlist Endpoint:
Modify the SQL query to fetch additional product details such as name, price, and images. This will allow the frontend to display all necessary information without making multiple API calls.
if (!userId) {
return res.status(400).json({ message: 'User ID not found in token' });
}
try {
const query = `
SELECT p.id, p.name, p.price, p.images
FROM wishlist w
JOIN products p ON w.product_id = p.id
WHERE w.user_id = $1
`;
const { rows } = await pool.query(query, [userId]);
res.status(200).json({ wishlist: rows });
} catch (error) {
console.error('Error fetching wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
However please for each wishlist item, fetch its product id by /products/[id]... and get the information from there...
To migrate your Wishlist component from using CORS credentials to Bearer tokens and enhance it by displaying each product's name and its cheapest price, follow the steps below. This includes updating both the frontend and backend as necessary, ensuring smooth and stable performance across all browsers, including Safari.
Overview
Backend Adjustments (Optional but Recommended)
Frontend Adjustments: Migrating to Bearer Tokens
Fetching Detailed Product Information
Displaying Product Name and Cheapest Price
Ensuring Design Smoothness and Safari Compatibility
Let's dive into each step in detail.
1. Backend Adjustments (Optional but Recommended)
While it's possible to fetch each product's details individually from the /products/[id] endpoint, it's more efficient to modify the /wishlist endpoint to return comprehensive product details. This reduces the number of API calls and enhances performance.
Enhanced getWishlist Endpoint
Modify your getWishlist controller to include name, price, and images for each product.
typescript
// controllers/wishlistController.ts
import { Request, Response } from 'express';
import { pool } from "../config/database";
// Fetch all product details from the user's wishlist
export const getWishlist = async (req: Request, res: Response) => {
const userId = req.user?.userId;
if (!userId) {
return res.status(400).json({ message: 'User ID not found in token' });
}
try {
const query = `
SELECT p.id, p.name, p.price, p.images
FROM wishlist w
JOIN products p ON w.product_id = p.id
WHERE w.user_id = $1
`;
const { rows } = await pool.query(query, [userId]);
res.status(200).json({ wishlist: rows });
} catch (error) {
console.error('Error fetching wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
Benefits:
Reduced API Calls: Eliminates the need to fetch each product's details separately.
Improved Performance: Fewer network requests lead to faster load times.
Simplified Frontend Logic: Easier data handling on the client side.
Note: If modifying the backend isn't feasible, you can proceed with fetching each product's details individually on the frontend as described in the subsequent steps.
2. Frontend Adjustments: Migrating to Bearer Tokens
To switch from using CORS credentials (credentials: 'include') to Bearer tokens, you'll need to update your fetch requests to include the Authorization header with the token.
Steps:
Store Token Securely: Ensure the Bearer token is stored securely, preferably in localStorage or more securely in HTTP-only cookies (recommended for sensitive applications).
Update API Calls:
Replace all instances where credentials: 'include' is used with the Authorization header containing the Bearer token.
Updated Wishlist Component
Here's the updated Wishlist component using Bearer tokens:
jsx
Key Changes:
Authorization Header:
Added the Authorization header with the Bearer token in both fetchWishlist and handleRemoveItem.
Optimistic UI Update:
Removed the dependency on useOptimistic for simplicity and directly updated the state with setWishlistItems.
Displaying Name and Price:
Passed name and price to the WishlistItem component.
Used the getCheapestPrice function to determine and format the price.
Design Enhancements:
Added subtle hover effects and transitions for better user experience.
Ensured buttons have hover states for better interactivity.
Error Handling:
Added checks for the presence of the token and handled cases where it's missing.
3. Fetching Detailed Product Information
If you opt not to modify the backend to return detailed product information, you need to fetch each product's details individually on the frontend. Here's how you can adjust your component accordingly.
First, fetch the list of product IDs from the /wishlist endpoint.
Fetch Product Details:
For each product ID, make a separate API call to /products/[id] to retrieve detailed information.
Update State:
Once all product details are fetched, update the wishlistItems state with the comprehensive product data.
Note: While this approach works, it's less efficient due to multiple network requests. Modifying the backend to return detailed product information in a single call is recommended for better performance.
4. Displaying Product Name and Cheapest Price
Ensure that each wishlist item displays the product's name and its cheapest price. The getCheapestPrice function is already defined; ensure it's used correctly.
Flexbox and Grid: Ensure that Flexbox and Grid layouts are used in a way that's compatible with Safari. Avoid properties or syntax not widely supported.
5.2. JavaScript Compatibility
Polyfills: If you use modern JavaScript features that aren't supported by older Safari versions, consider using polyfills.
bash
npm install core-js
Then, in your next.config.js or a setup file, include the necessary polyfills.
Avoid Unsupported Features: Double-check that all used JavaScript features are supported by the target Safari versions.
5.3. Image Optimization
Image Formats: Ensure that the image formats used are compatible with Safari. While JPEG and PNG are widely supported, newer formats like WebP have limited support in older versions.
Debounce Search Inputs: If implementing search functionality, debounce the input to prevent excessive API calls.
5.6. Accessibility
ARIA Attributes: Ensure buttons and interactive elements have appropriate ARIA attributes.
Keyboard Navigation: Ensure that all interactive elements are accessible via keyboard.
Contrast Ratios: Maintain sufficient contrast ratios for text and interactive elements for readability.
Final Thoughts
By following the steps outlined above, you can successfully migrate your Wishlist component to use Bearer tokens, enhance it by displaying product names and their cheapest prices, and ensure it remains smooth and stable across all browsers, including Safari.
Key Takeaways:
Security: Using Bearer tokens enhances security by explicitly handling authentication.
Performance: Fetching detailed product information in a single API call (by enhancing the backend) optimizes performance.
User Experience: Implementing design improvements and ensuring cross-browser compatibility provides a seamless user experience.
Maintainability: Structuring your code with clear separations and optimizations makes it easier to maintain and scale.
Feel free to reach out if you need further assistance or clarifications!