Nextjs tạo sort

Nextjs tạo sort

Tạo chức năng sort cho nextjs như sau :

'use client';

import React, { useEffect, useState } from 'react';

type ProductType = {
     id: number;
     title: string;
     description: string;
     category: string;
     price: number;
};

const Listproduct = () => {
     const [mode, setMode] = useState<'desc' | 'asc' | 'recent'>('desc');
     const [product, setProduct] = useState<ProductType[]>([]);
     const [loading, setLoading] = useState(false);
     useEffect(() => {
          const fetchPosts = async (sort: string) => {
               setLoading(true);
               try {
                    const res = await fetch(`https://dummyjson.com/products?sortBy=title&order=${sort}`);
                    const data = await res.json();

                    setProduct(data.products);
               } catch (error) {
                    console.error('Lỗi khi tải bài viết:', error);
               } finally {
                    setLoading(false);
               }
          };
          fetchPosts(mode);
     }, [mode]);

     return (
          <div>
               <div className="flex gap-4 mb-4">
                    <button
                         onClick={() => setMode('asc')}
                         className={`sortbt ${mode === 'asc' ? 'active' : ''}`}
                    >
                         Mới nhất
                    </button>

                    <button
                         onClick={() => setMode('desc')}
                         className={`sortbt ${mode === 'desc' ? 'active' : ''}`}
                    >
                         Mặc định
                    </button>

                    {/* <button
                         onClick={() => setMode('recent')}
                         className={`sortbt ${mode === 'recent' ? 'active' : ''}`}
                    >
                         Gần đây
                    </button> */}
               </div>

               {loading ? (
                    <p>Đang tải bài viết...</p>
               ) : (
                    <ul className="space-y-2">
                         {product.map((item: ProductType) => (
                              <li key={item.id} className="border p-2 rounded">
                                   <h4>{item.title}</h4>
                                   <p className="text-sm text-gray-500">{item.description}</p>
                              </li>
                         ))}
                    </ul>
               )}
          </div>
     );
};

export default Listproduct;