Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 84 additions & 12 deletions src/app/[locale]/(main)/user/wishlist/page.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
"use client"
import { retrieveCustomer } from "@/lib/data/customer"
import { redirect } from "next/navigation"
import { isEmpty } from "lodash"
Expand All @@ -7,23 +8,84 @@ import { Button } from "@/components/atoms"
import { WishlistItem } from "@/components/cells"
import { getUserWishlists } from "@/lib/data/wishlist"
import { HttpTypes } from "@medusajs/types"
import { UserNavigation } from "@/components/molecules"
import { SelectField, UserNavigation } from "@/components/molecules"
import { ProductsPagination } from "@/components/organisms"
import { useEffect, useState } from "react"
import { usePagination } from "@/hooks/usePagination"

export default async function Wishlist() {
const user = await retrieveCustomer()
const ITEMS_PER_PAGE = 10

let wishlist: WishlistType[] = []
if (user) {
const response = await getUserWishlists()
wishlist = response.wishlists
const sortOptions = [
{ label: "Newest", value: "created_at" },
{ label: "Price: Low to High", value: "price_asc" },
{ label: "Price: High to Low", value: "price_desc" },
]
Comment on lines +18 to +22
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this already exists in code, how about moving this to consts?


export default function Wishlist() {
const [user, setUser] = useState<any>(null)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please type this without any

const [wishlist, setWishlist] = useState<WishlistType[]>([])
const [sortBy, setSortBy] = useState("created_at")
const [loading, setLoading] = useState(true)
const [totalCount, setTotalCount] = useState(0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the point of tocalCount, if it's not used anywhere anyway?

const { currentPage, setPage } = usePagination()

useEffect(() => {
const fetchData = async () => {
setLoading(true)
const userData = await retrieveCustomer()

if (!userData) {
redirect("/user")
}

setUser(userData)

const response = await getUserWishlists()
setWishlist(response.wishlists)
setTotalCount(response.count)
setLoading(false)
}

fetchData()
}, [])

const sortProducts = (products: any[]) => {
if (!products) return []

return [...products].sort((a, b) => {
if (sortBy === "created_at") {
return new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
} else if (sortBy === "price_asc") {
return a.calculated_amount - b.calculated_amount
} else if (sortBy === "price_desc") {
return b.calculated_amount - a.calculated_amount
}
return 0
})
Comment on lines +52 to +64
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. couldn't we sort on BE side?
  2. if we don't, there's helper function for FE sorting in lib/helpers

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course, the only right way is to do it on BE side.

}

const count = wishlist?.[0]?.products?.length || 0
const handleSortChange = (value: string) => {
setSortBy(value)
if (currentPage !== 1) {
setPage('1')
}
}

if (!user) {
redirect("/user")
if (loading) {
return <div className="container">Loading...</div>
}

const allProducts = wishlist?.[0]?.products || []
const count = allProducts.length || 0

const sortedAllProducts = sortProducts(allProducts)

const totalPages = Math.ceil(count / ITEMS_PER_PAGE) || 1

const startIndex = (currentPage - 1) * ITEMS_PER_PAGE
const endIndex = startIndex + ITEMS_PER_PAGE
const sortedProducts = sortedAllProducts.slice(startIndex, endIndex)

return (
<main className="container">
<div className="grid grid-cols-1 md:grid-cols-4 mt-6 gap-5 md:gap-8">
Expand All @@ -45,10 +107,19 @@ export default async function Wishlist() {
<div className="flex flex-col gap-6">
<h2 className="heading-lg text-primary uppercase">Wishlist</h2>
<div className="flex justify-between items-center">
<p>{count} listings</p>
<p>{count} listings (showing {sortedProducts.length} on this page)</p>
<div className="flex gap-2 items-center">
Sort by:{' '}
<SelectField
className="min-w-[200px]"
options={sortOptions}
selected={sortBy}
selectOption={handleSortChange}
/>
</div>
</div>
<div className="flex flex-wrap max-md:justify-center gap-4">
{wishlist?.[0].products?.map((product) => (
{sortedProducts.map((product) => (
<WishlistItem
key={product.id}
product={
Expand All @@ -62,6 +133,7 @@ export default async function Wishlist() {
/>
))}
</div>
<ProductsPagination pages={totalPages} />
</div>
)}
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/cells/WishlistItem/WishlistItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const WishlistItem = ({
)}
>
<div className="relative w-full h-full bg-primary aspect-square">
<div className="absolute right-3 top-3 z-10 cursor-pointer">
<div className="absolute right-3 top-3 z-[1] cursor-pointer">
<WishlistButton
productId={product.id}
wishlist={wishlist}
Expand Down
18 changes: 16 additions & 2 deletions src/lib/data/wishlist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,30 @@ import { sdk } from "../config"
import { getAuthHeaders } from "./cookies"
import { revalidatePath } from "next/cache"

export const getUserWishlists = async () => {
export const getUserWishlists = async ({
page = 1,
limit = 12,
}: {
page?: number
limit?: number
} = {}) => {
const headers = {
...(await getAuthHeaders()),
"Content-Type": "application/json",
"x-publishable-api-key": process.env
.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY as string,
}

// Calculate offset from page number
const offset = (page - 1) * limit

const queryParams = new URLSearchParams({
offset: offset.toString(),
limit: limit.toString(),
}).toString()

return sdk.client
.fetch<{ wishlists: Wishlist[]; count: number }>(`/store/wishlist`, {
.fetch<{ wishlists: Wishlist[]; count: number }>(`/store/wishlist?${queryParams}`, {
cache: "no-cache",
headers,
method: "GET",
Expand Down