export type SortOption = {
field: 'price' | 'createdAt';
direction: 'asc' | 'desc';
};
const ListingPage = () => {
const [properties, setProperties] = useState<PropertiesState>({
data: [],
metadata: { totalDataCount: 0 },
});
const [loading, setLoading] = useState<boolean>(false);
const searchParams = useSearchParams();
const sort = searchParams.get('sort') || 'createdAt-desc';
const [sortField, sortDirection] = sort.split('-') as [
SortOption['field'],
SortOption['direction']
];
const currentPage = Number(searchParams.get('page')) || 1;
const sort = searchParams.get('sort') || 'createdAt-desc';
const paginationInfo = usePagination({
totalItems: totalListings,
itemsPerPage,
currentPage,
});
const pageNumbers = usePageNumbers(paginationInfo);
const createQueryString = useCallback(
(params: Record<string, string>) => {
const newSearchParams = new URLSearchParams(searchParams.toString());
Object.entries(params).forEach(([key, value]) => {
newSearchParams.set(key, value);
});
return newSearchParams.toString();
},
[searchParams]
);
const handlePageChange = useCallback(
async (page: number) => {
router.push(`?${createQueryString({ page: page.toString() })}`);
await scrollToListings();
},
[router, createQueryString, scrollToListings]
);
const handleSortChange = useCallback(
(option: SortOption) => {
const sortString = `${option.field}-${option.direction}`;
router.push(`?${createQueryString({ sort: sortString, page: '1' })}`);
},
[router, createQueryString]
);
useEffect(() => {
const fetchProperties = async () => {
setLoading(true);
try {
const fetchedListings = await fetchAllListings(currentPage, 12, sortField, sortDirection);
console.log('fetchedListings', fetchedListings);
setProperties({ data: fetchedListings.data, metadata: fetchedListings.metadata });
} catch (error) {
console.error('Error fetching properties:', error);
toast({
variant: 'destructive',
title: 'Error fetching properties',
description: 'An error occurred while posting new property',
});
} finally {
setLoading(false);
}
};
fetchProperties();
}, [currentPage]);
const sortedProperties = [...properties.data].sort((a, b) => {
const multiplier = sortDirection === 'asc' ? 1 : -1;
return multiplier * (a[sortField] > b[sortField] ? 1 : -1);
});
const totalListings = properties.metadata.totalDataCount;