frontend: add specific hook to fetch data for the feed

Pedro Lucas Porcellis porcellis@eletrotupi.com 22 days ago 6b5692bd7b0965769ac35dc7432b86babe675797
Parents: 9964daf
2 file(s) changed
  • frontend/hooks/useHistoryFeed.ts +31 -0
  • frontend/lib/utils/history.ts +31 -0
frontend/hooks/useHistoryFeed.ts
@@ -0,0 +1,31 @@
1 + // hooks/useHistoryFeed.ts
2 + import { useMemo } from 'react'
3 + import { mergeAndSort, filterByCategory, groupByDate } from '@/lib/utils/history'
4 + import {
5 + mapMoodToHistoryCard,
6 + mapSleepToHistoryCard,
7 + mapTriggerToHistoryCard,
8 + mapInterventionToHistoryCard
9 + } from '@/lib/history/mappers'
10 + import type { HistoryCategory } from '@/lib/history/types'
11 + import { useMoodEntries, useSleepRecords } from '@/hooks';
12 +
13 + export function useHistoryFeed(activeFilter: HistoryCategory | 'all') {
14 + const { data: moodsPage } = useMoodEntries({})
15 + const { data: sleepPage } = useSleepRecords({})
16 +
17 + const moods = moodsPage?.entries ?? []
18 + const sleepRecords = sleepPage?.entries ?? []
19 +
20 + const grouped = useMemo(() => {
21 + const merged = mergeAndSort([
22 + moods.map(mapMoodToHistoryCard),
23 + sleepRecords.map(mapSleepToHistoryCard),
24 + ])
25 + const filtered = filterByCategory(merged, activeFilter)
26 + return groupByDate(filtered)
27 + }, [moods, sleepRecords, activeFilter])
28 +
29 + // TODO: expose the isLoading here
30 + return grouped
31 + }
frontend/lib/utils/history.ts
@@ -0,0 +1,31 @@
1 + // TODO: add a barrel import here ffs
2 + import type { HistoryCard, HistoryCategory } from '@/lib/history/types'
3 +
4 + export function mergeAndSort(cards: HistoryCard[][]): HistoryCard[] {
5 + return cards
6 + .flat()
7 + .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
8 + }
9 +
10 + export function groupByDate(cards: HistoryCard[]): Record<string, HistoryCard[]> {
11 + return cards.reduce<Record<string, HistoryCard[]>>((acc, card) => {
12 + const key = new Date(card.timestamp).toLocaleDateString('pt-BR', {
13 + weekday: 'long',
14 + day: 'numeric',
15 + month: 'long',
16 + });
17 +
18 + // XXX: Hacky as fuck
19 + (acc[key] ??= []).push(card)
20 +
21 + return acc
22 + }, {})
23 + }
24 +
25 + export function filterByCategory(
26 + cards: HistoryCard[],
27 + active: HistoryCategory | 'all',
28 + ): HistoryCard[] {
29 + if (active === 'all') return cards
30 + return cards.filter(c => c.category === active)
31 + }