|
1 | | -"use client"; |
| 1 | +"use client" |
2 | 2 |
|
3 | | -import { useEffect, useState } from "react"; |
4 | | -import { useRouter, useSearchParams } from "next/navigation"; |
5 | 3 | import { Post } from "@/interfaces/post"; |
6 | 4 | import { TitlePreview } from "@/app/_components/post_gen/title-preview"; |
| 5 | +import { usePostSort } from "@/app/_hooks/usePostSort"; |
7 | 6 |
|
8 | 7 | type Props = { |
9 | 8 | posts: Post[]; |
| 9 | + skipURLParam?: boolean; // for MDX usage |
10 | 10 | }; |
11 | 11 |
|
12 | | -export function MoreStoriesConcise({ posts }: Props) { |
13 | | - const router = useRouter(); |
14 | | - const searchParams = useSearchParams(); |
15 | | - |
16 | | - const defaultSort = searchParams.get("sort") === "date" ? "date" : "title"; |
17 | | - const [sortBy, setSortBy] = useState<"title" | "date">(defaultSort); |
18 | | - |
19 | | - // Sync localStorage on sort change |
20 | | - useEffect(() => { |
21 | | - localStorage.setItem("preferredSort", sortBy); |
22 | | - }, [sortBy]); |
23 | | - |
24 | | - // If no URL param, check localStorage once on load |
25 | | - useEffect(() => { |
26 | | - const saved = localStorage.getItem("preferredSort"); |
27 | | - if (!searchParams.get("sort") && saved) { |
28 | | - setSortBy(saved === "date" ? "date" : "title"); |
29 | | - router.replace(`?sort=${saved}`); |
30 | | - } |
31 | | - }, []); |
32 | | - |
33 | | - // Apply sorting |
34 | | - const sortedPosts = [...posts].sort((a, b) => { |
35 | | - if (sortBy === "title") return a.title.localeCompare(b.title); |
36 | | - return new Date(b.date).getTime() - new Date(a.date).getTime(); |
37 | | - }); |
38 | | - |
39 | | - // Handle button click |
40 | | - const handleSortChange = (mode: "title" | "date") => { |
41 | | - setSortBy(mode); |
42 | | - router.replace(`?sort=${mode}`); |
43 | | - }; |
| 12 | +export function MoreStoriesConcise({ posts, skipURLParam }: Props) { |
| 13 | + const { sortedPosts, sortBy, handleSortChange } = usePostSort(posts, skipURLParam); |
44 | 14 |
|
45 | 15 | return ( |
46 | 16 | <section> |
|
0 commit comments