Skip to content

Commit

Permalink
Merge pull request #49 from atlp-rwanda/buyer-bug-fix
Browse files Browse the repository at this point in the history
buyer frontend bug fix
  • Loading branch information
niyontwali authored Jul 30, 2024
2 parents 0cfb527 + d36aaa0 commit 809d9c6
Show file tree
Hide file tree
Showing 11 changed files with 84 additions and 50 deletions.
1 change: 0 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ const App = () => {
dispatch<any>(productsApi.endpoints.getProducts.initiate());
if (isAuthenticated) {
dispatch<any>(cartApi.endpoints.getCarts.initiate());
console.log('Cart');
}
}, [dispatch]);

Expand Down
4 changes: 2 additions & 2 deletions src/components/Products/ProductCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@ const ProductCard: React.FC<ProductCardProps> = ({ product, cartAdded, wishList,
window.open(`/products/${product.id}`, '_blank');
// window.scrollTo({ top: 0, behavior: 'smooth' });
}}
className='bg-whiteColor flex-col relative w-[49%] sm:w-52 md:w-[32.5%] lg:w-[19%] 2xl:w-[253px] mb-2 drop-shadow-md rounded-lg cursor-pointer'
className='bg-whiteColor min-w-[140px] flex-col relative w-[49%] sm:min-w-52 md:w-[32.5%] lg:w-[19%] 2xl:w-[253px] mb-2 drop-shadow-md rounded-lg cursor-pointer'
>
<div className='product-image flex justify-center w-full rounded-tl-lg rounded-tr-lg relative'>
<img src={imageUrl} alt={product.name} className='w-full h-52 md:h-60 rounded-tl-lg rounded-tr-lg object-cover object-top' />
<img src={imageUrl} alt={product.name} className='w-full h-52 sm:object-center md:h-60 rounded-tl-lg rounded-tr-lg object-cover object-top' />
<div className='absolute bottom-2 right-2 flex flex-col gap-1'>
{cartAdded
? (
Expand Down
3 changes: 1 addition & 2 deletions src/components/authentication/LoginComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const LoginComponent = () => {

const [loginUser, { data: loginData, error, isLoading, isSuccess: isLoginSuccess, isError }] = useLoginUserMutation();

const { data: userData, isSuccess: isUserSuccess } = useGetUserByIdQuery(userId, { skip: !isLoginSuccess });
const { data: userData, isSuccess: isUserSuccess } = useGetUserByIdQuery(userId, { skip: !userId });

useEffect(() => {
if (isError && error) {
Expand Down Expand Up @@ -140,7 +140,6 @@ const LoginComponent = () => {
>
{isSubmitting || isLoading ? 'Loading...' : 'Sign In'}
</button>
{isLoginSuccess && <p className='text-green-600 text-xs font-normal'>Login successful!</p>}
<span className='self-center font-bold text-grayColor'>or</span>
<button
onClick={handleGoogleAuthentication}
Expand Down
15 changes: 10 additions & 5 deletions src/components/cart/Cart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@ import CartItem from './CartItem';
import { Link } from 'react-router-dom';
import { ICartProduct, ICartsHookResponse, ICartsResponse } from '../../utils/schemas';
import { useGetCartsQuery } from '../../services/cartApi';
import { useSelector } from 'react-redux';
import { RootState } from '../../redux/store';

const Cart: React.FC = () => {
// const isAuthenticated = useSelector((state: RootState) => state.user.token ? true : false);
const isAuthenticated = useSelector((state: RootState) => state.user.token);
const {
data: carts,
isLoading,
isSuccess,
isError,
error,
} = useGetCartsQuery<ICartsResponse>() as ICartsHookResponse;
} = useGetCartsQuery<ICartsResponse>(undefined, { skip: !isAuthenticated }) as ICartsHookResponse;
const [totalPrice, setTotalPrice] = useState(0);
const [items, setItems] = useState(0);

Expand Down Expand Up @@ -50,7 +51,7 @@ const Cart: React.FC = () => {
);
content = renderedCart;
} else if (isError) {
content = <div>{error?.toString()}</div>;
content = <div className='text-center text-sm'>Your cart is empty</div>;
}

return (
Expand All @@ -71,7 +72,11 @@ const Cart: React.FC = () => {
</div>
<Link
to='/checkoutbag'
className='leading-none bg-greenColor hover:bg-[#1a6461] rounded-full px-5 py-3 text-whiteColor font-medium text-xs transition-all delay-75 ease-in cursor-pointer text-center'
className={`leading-none bg-greenColor hover:bg-[#1a6461] rounded-full px-5 py-3 text-whiteColor font-medium text-xs transition-all delay-75 ease-in cursor-pointer text-center ${items === 0 ? 'bg-gray-400 cursor-not-allowed' : 'bg-greenColor hover:bg-[#1a6461]'}`}
style={{
pointerEvents: items === 0 ? 'none' : 'auto',
opacity: items === 0 ? 0.5 : 1,
}}
>
Checkout
</Link>
Expand Down
3 changes: 2 additions & 1 deletion src/components/cart/CartItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const CartItem: React.FC<CartItemsProps> = ({ id, name, image, sizes, quantity,
const [updateCart] = useUpdateCartMutation()
const [deleteCart, { isLoading }] = useDeleteCartMutation()
const currentPrice = price;
console.log(sizes)

useEffect(() => {
setItemTotalPrice(currentPrice * quantity);
Expand Down Expand Up @@ -44,7 +45,7 @@ const CartItem: React.FC<CartItemsProps> = ({ id, name, image, sizes, quantity,
<div className="flex flex-col gap-1 font-light mt-1 md:gap-1">
<label htmlFor="size" className="leading-none text-xs opacity-70">Size</label>
<div id="size" className="border border-greenColor rounded-full h-9 p-[6px] text-sm bg-whiteColor w-4/5 font-medium outline-none md:w-1/2 justify-start flex items-center leading-none px-3">
{sizes[0].size !== null ? sizes[0].size : 'One'}
{sizes[0].size !== "" ? sizes[0].size : 'One'}
</div>
</div>
<div className="flex flex-col font-light gap-1 mt-2">
Expand Down
19 changes: 15 additions & 4 deletions src/components/navbar/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { RootState } from '../../redux/store';
import { selectAllCarts } from '../../services/cartApi';

const Navbar: React.FC = () => {
const isAuthenticated = useSelector((state: RootState) => state.user.token);
const cartsCount = useSelector(selectAllCarts).length
const [notificationOpen, setNotificationOpen] = useState<boolean>(false);
const navbarRef = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -96,6 +97,14 @@ const Navbar: React.FC = () => {
}
setUserInfo(['Anynmous', 'Anoonymous']);
}, [isUserFetched]);

const handleCartClick = () => {
if (!isAuthenticated) {
navigate('/login', { replace: true });
} else {
SetCartOpen(state => !state);
}
};
return (
<>
{(wish || cartOpen || notificationOpen) && (
Expand Down Expand Up @@ -179,7 +188,7 @@ const Navbar: React.FC = () => {
{/* <span className='absolute top-1 right-1 w-2 h-2 rounded-full bg-redColor'></span> */}
</a>
<div
onClick={() => SetCartOpen(state => !state)}
onClick={handleCartClick}
className='rounded-full transition-all ease-in-out delay-100 hover:bg-grayColor active:bg-greenColor active:text-blackColor hover:text-blackColor p-1 select-none'
>
<div className='relative'>
Expand All @@ -197,9 +206,11 @@ const Navbar: React.FC = () => {
d='M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 0 0-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 0 0-16.536-1.84M7.5 14.25 5.106 5.272M6 20.25a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm12.75 0a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Z'
/>
</svg>
<span className='p-1 leading-none text-[9px] bg-redColor text-whiteColor rounded-full flex justify-center items-center w-5 h-5 md:w-6 md:h-6 md:text-xs absolute -top-1 -right-1 md:-right-2 md:-top-2'>
{cartsCount}
</span>
{isAuthenticated && (
<span className='p-1 leading-none text-[9px] bg-redColor text-whiteColor rounded-full flex justify-center items-center w-5 h-5 md:w-6 md:h-6 md:text-xs absolute -top-1 -right-1 md:-right-2 md:-top-2'>
{cartsCount}
</span>
)}
</div>
{cartOpen && (
<div
Expand Down
12 changes: 10 additions & 2 deletions src/components/navbar/cartNav/CartNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { selectAllCarts } from '../../../services/cartApi';

const CartNav: React.FC = () => {
const carts = useSelector(selectAllCarts);

const cartsLength = carts.length;
return (
<>
<div className='absolute w-[360px] right-2 md:right-4 top-12 md:top-14 mt-2 z-[55] bg-whiteColor text-blackColor rounded-md border border-grayColor shadow-customShadow'>
Expand Down Expand Up @@ -47,7 +47,15 @@ const CartNav: React.FC = () => {
</div>
<div className='py-2 flex justify-center gap-3 mt-2'>
<NavLink to="/shoppingcart" className='flex-grow rounded-full border border-greenColor text-sm py-2 px-2 hover:border-[#1a6461] transition-all delay-75 ease-in cursor-pointer text-center'>View Cart</NavLink>
<NavLink to="/checkoutbag" className='flex-grow rounded-full border border-greenColor text-sm py-2 px-2 bg-greenColor text-whiteColor transition-all delay-75 ease-in cursor-pointer hover:bg-[#1a6461] text-center'>Checkout</NavLink>
<NavLink
to="/checkoutbag"
className={`flex-grow rounded-full border border-greenColor text-sm py-2 px-2 bg-greenColor text-whiteColor transition-all delay-75 ease-in cursor-pointer hover:bg-[#1a6461] text-center ${cartsLength === 0 ? 'bg-gray-400 cursor-not-allowed' : 'bg-greenColor hover:bg-[#1a6461]'}`}
style={{
pointerEvents: cartsLength === 0 ? 'none' : 'auto',
opacity: cartsLength === 0 ? 0.4 : 1,
}}

>Checkout</NavLink>
</div>
</div>
</div>
Expand Down
10 changes: 5 additions & 5 deletions src/containers/FeaturedProducts/FeaturedProducts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import { Product } from '../../types/Types';
import { useGetProductsQuery } from '../../services/productApi';
import { useGetCartsQuery } from '../../services/cartApi';
import { useGetUserWishlistQuery } from '../../services/wishlistApi';
// import { useSelector } from 'react-redux';
// import { RootState } from '../../redux/store';
import { useSelector } from 'react-redux';
import { RootState } from '../../redux/store';


export default function FeaturedProduct() {
// const isAuthenticated = useSelector((state: RootState) => state.user.token) ? true : false;
const isAuthenticated = useSelector((state: RootState) => state.user.token);
const { data: productsList, isLoading, isSuccess } = useGetProductsQuery()
const { data: cartList, isLoading: cartListLoading } = useGetCartsQuery()
const { data: wishList, isLoading: wishLoading } = useGetUserWishlistQuery()
const { data: cartList, isLoading: cartListLoading } = useGetCartsQuery(undefined, { skip: !isAuthenticated })
const { data: wishList, isLoading: wishLoading } = useGetUserWishlistQuery(undefined, { skip: !isAuthenticated })
const product = productsList?.data
let content;
if (isLoading && cartListLoading && wishLoading) {
Expand Down
9 changes: 6 additions & 3 deletions src/containers/buyer/WishList.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { useEffect } from 'react';
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useGetUserWishlistQuery, useClearWishlistMutation } from '../../services/wishlistApi';
import { clearWishLists, setWishLists } from '../../redux/slices/wishlistSlice';
import { RootState } from '../../redux/store';

function WishList() {
const dispatch = useDispatch();
const { data, isLoading } = useGetUserWishlistQuery();
const isAuthenticated = useSelector((state: RootState) => state.user.token);
const authenticated = isAuthenticated !== null;
const { data, isLoading } = useGetUserWishlistQuery(undefined, { skip: !authenticated });
const [clearWishlist] = useClearWishlistMutation();
const wishlistItems = useSelector((state: any) => state.wishlist.items);

Expand Down Expand Up @@ -38,7 +41,7 @@ function WishList() {
<div className="text-xl text-gray-500">No items in your wishlist</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{wishlistItems.map((item:any) => (
{wishlistItems.map((item: any) => (
<div
key={item.id}
className="product-card bg-white shadow-lg rounded-lg p-4 m-4 transition-transform hover:scale-105 cursor-pointer"
Expand Down
47 changes: 28 additions & 19 deletions src/pages/product/ProductDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import ProductReviewCard from '../../components/Products/ProductReviewCard';
import { ImageToggle } from '../../components/Products/ImageToggle';
import { ImageCard } from '../../components/Products/ImageCard';
import { ColorComponent } from '../../components/Products/ColorComponent';
import { useGetProductByIdQuery } from '../../services/productApi';
import { useGetProductByIdQuery, useGetProductsQuery } from '../../services/productApi';
import { useState, useEffect } from 'react';
import Footer from '../../components/footer/Footer';
import { useAddProductToWishlistMutation, useGetUserWishlistQuery } from '../../services/wishlistApi';
import ProductDetailSkeleton from '../../containers/ProductDetail/ProductDetailSkeleton';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { useAddProductToCartMutation } from '../../services/cartApi';
import { useAddProductToCartMutation, useGetCartsQuery } from '../../services/cartApi';
import { toast } from 'react-toastify';
import { QueryErrorData } from '../../utils/schemas';
import { useSelector } from 'react-redux';
Expand All @@ -36,14 +36,15 @@ export const ProductDetail = () => {
const [addProductToWishlist] = useAddProductToWishlistMutation();
const [addProductToCart, { isLoading: cartLoading }] = useAddProductToCartMutation();
const { data } = useGetUserWishlistQuery(undefined, { skip: !authenticated });
const products: Product[] = useSelector((state: RootState) => state.products.productsDataList);
const { data: cartList } = useGetCartsQuery(undefined, { skip: !isAuthenticated })
const { data: products, isSuccess } = useGetProductsQuery()

const [spottedImage, setSpottedImage] = useState<string | null>(null);
const [selectedSize, setSelectedSize] = useState<Size | undefined>();
const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false);
const [isInWishlist, setIsInwishlist] = useState(false);
const recommendedProductsRef = useRef<HTMLDivElement>(null);
let similarProducts: Product[] = [];
let similarProducts: Product[] | undefined = [];

useEffect(() => {
if (productData) {
Expand All @@ -59,8 +60,9 @@ export const ProductDetail = () => {
setIsInwishlist(data.data.some((size: any) => selectedSize.id === size.productId));
}
}, [data, selectedSize]);

similarProducts = products.filter(product => product.categoryId === productData?.data.categoryId);
if (isSuccess) {
similarProducts = products.data?.filter(product => product.categoryName === productData?.data.categoryName);
}

if (productLoading) {
return <ProductDetailSkeleton />;
Expand Down Expand Up @@ -146,7 +148,7 @@ export const ProductDetail = () => {
toast.success(message, toastConfig);
}
// eslint-disable-next-line no-empty
} catch (error) {}
} catch (error) { }
};

// FUNCTION TO HANDLE SIZE CHANGES AND RENDER THE VALUES ASSOCIATED WITH PRODUCT SIZE LIKE PRICE....
Expand Down Expand Up @@ -226,16 +228,15 @@ export const ProductDetail = () => {
className='border-greenColor border-2 rounded-full lg:py-2 text-sm px-2 bg-whiteColor w-1/2 outline-none hover:cursor-pointer'
onChange={e => handleSizeChange(e)}
>
{productData.data.sizes.map(size => (
<option key={size.size}>{size.size}</option>
))}
{productData.data.sizes.map(size => {
return <option key={size.size}>{size.size === '' ? 'One' : size.size}</option>
})}
</select>
<div
className={`flex border-2 items-center transition-all py-1 px-6 gap-4 rounded-full w-1/2 border-blackColor ${
isInWishlist
? 'bg-greenColor text-whiteColor border-2 border-greenColor cursor-not-allowed'
: 'hover:bg-greenColor hover:text-whiteColor hover:border-2 hover:border-greenColor hover:cursor-pointer'
}`}
className={`flex border-2 items-center transition-all py-1 px-6 gap-4 rounded-full w-1/2 border-blackColor ${isInWishlist
? 'bg-greenColor text-whiteColor border-2 border-greenColor cursor-not-allowed'
: 'hover:bg-greenColor hover:text-whiteColor hover:border-2 hover:border-greenColor hover:cursor-pointer'
}`}
onClick={!isInWishlist ? handleAddToWishlist : undefined}
>
{isInWishlist ? <FaHeart size='20px' /> : <FaRegHeart size='20px' />}
Expand Down Expand Up @@ -307,11 +308,19 @@ export const ProductDetail = () => {
/>
<div
ref={recommendedProductsRef}
className='flex overflow-scroll gap-4 lg:gap-8 py-2 scrollbar scroll-smooth'
className='flex w-full px-1 overflow-scroll gap-4 py-2 scrollbar scroll-smooth'
>
{similarProducts.map(product => (
<ProductCard key={product.id} product={product} />
))}
{similarProducts?.map(product => {
const wishListed = data?.data.find(item => item.productId === product.sizes[0].id)
const wishListId = wishListed?.id
return <ProductCard
key={product.id}
product={product}
cartAdded={cartList?.cartProducts.some((cartProduct) => cartProduct.id === product.id)}
wishList={data?.data.some((wishList) => wishList.productId === product.sizes[0].id)}
wishListId={wishListId}
/>
})}
</div>
<ImageToggle
handleClick={() => scrollRecommendedProducts('right')}
Expand Down
11 changes: 5 additions & 6 deletions src/services/userApi.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { mavericksApi } from '.';
import { User } from '../types/Types';

const id = localStorage.getItem('user');

export const userApi = mavericksApi.injectEndpoints({
endpoints: builder => ({
getUserById: builder.query({
query: () => ({
url: `users/user/${id}`,
}),
query: (userId) => {
return {
url: `users/user/${userId}`,
}
},
}),
getUsers: builder.query<{ message: User[] }, void>({
query: () => ({
Expand All @@ -22,7 +22,6 @@ export const userApi = mavericksApi.injectEndpoints({
query: () => ({
url: 'users/role/seller',
headers: {
Authorization: localStorage.getItem('token') || '',
},
}),
}),
Expand Down

0 comments on commit 809d9c6

Please sign in to comment.