Skip to content

Commit

Permalink
Add button to filter comments by date
Browse files Browse the repository at this point in the history
  • Loading branch information
camilovegag committed Apr 29, 2024
1 parent 892d8c1 commit 44f10ea
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions packages/berlin/src/pages/Option.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ function Option() {
>([]);
const [localOptionHearts, setLocalOptionHearts] = useState(0);
const [comment, setComment] = useState('');
const [sortOrder, setSortOrder] = useState('desc'); // 'asc' for ascending, 'desc' for descending

const { data: option, isLoading } = useQuery({
queryKey: ['option', optionId],
Expand All @@ -59,11 +60,15 @@ function Option() {
enabled: !!optionId,
});

const sortedComments = comments?.sort((a, b) => {
const dateA = new Date(a.createdAt).getTime();
const dateB = new Date(b.createdAt).getTime();
return dateB - dateA; // Sort by newest first
});
const sortedComments = useMemo(() => {
if (!comments) return [];

return comments.sort((a, b) => {
const dateA = new Date(a.createdAt).getTime();
const dateB = new Date(b.createdAt).getTime();
return sortOrder === 'desc' ? dateB - dateA : dateA - dateB;
});
}, [comments, sortOrder]);

useEffect(() => {
if (optionId) {
Expand Down Expand Up @@ -172,7 +177,20 @@ function Option() {
</Form>
{sortedComments && (
<>
<Title>Total comments ({sortedComments.length})</Title>
<FlexRow $justify="space-between">
<Title>Total comments ({sortedComments.length})</Title>
<IconButton
onClick={() => setSortOrder((prevOrder) => (prevOrder === 'asc' ? 'desc' : 'asc'))}
icon={{
src: `/icons/filter-${theme}.svg`,
alt: 'Filter icon',
}}
$padding={4}
$color="secondary"
$height={28}
$width={28}
/>
</FlexRow>
{sortedComments.map((comment) => (
<CommentCard key={comment.id} comment={comment} />
))}
Expand Down

0 comments on commit 44f10ea

Please sign in to comment.