refactor(fe): replace TanStack Query with SWR + UI/data cleanup
Build & Deploy (Nix) / build-and-deploy (backend) (push) Successful in 2m56s
Build & Deploy (Nix) / build-and-deploy (discord-gateway) (push) Successful in 3m42s
Build & Deploy (Nix) / build-and-deploy (proxy) (push) Successful in 3m59s

Rombak data layer frontend:
- Hapus @tanstack/react-query (package.json, lockfile, provider di
  dashboard layout) — ganti SWR 2.4.2 + SWRConfig (revalidateOnFocus
  false, deduping 10s, no retry on 404)
- Semua hooks data ditulis ulang ke useSWR; useAction() helper baru
  pengganti useMutation dengan surface kompatibel (mutate/mutateAsync/
  isPending/error)
- useMessages + useMessagesHasMore share satu SWR key — probe cursor
  yang tadinya dobel fetch API sekarang deduped
- WS sync (messages/media/recordings) pindah dari queryClient ke
  SWR mutate dengan filter key + revalidate:false
- useMessageSearch() dipakai search-panel & search-overlay; search
  overlay backdrop div -> button (fix a11y lint)

Rapikan UI + isi data:
- Tab stats recordings: placeholder 'coming soon' diganti stat asli
  (total, ukuran, speaker unik, top speakers)
- Empty states konsisten via EmptyState (images/review/recordings),
  EmptyState terima className
- biome check --write: 0 error, 8 warning pre-existing
- Verifikasi: tsc --noEmit PASS, next build PASS (11 halaman static),
  API live dicek — semua endpoint dashboard/messages/guilds/config/
  voice/media/recordings/review balikin data
This commit is contained in:
asepharyana
2026-08-01 09:19:39 +07:00
parent 1f91f99de3
commit 01c18b2060
26 changed files with 5145 additions and 329 deletions
+110 -91
View File
@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { messagesApi, voiceApi } from "@/lib/api";
import type { AttachmentRecord, Channel, MessageRecord } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook";
@@ -14,44 +14,48 @@ const msgKeys = {
review: (channelId?: string) =>
["messages-review", channelId ?? "__all__"] as const,
detail: (id: string) => ["message-detail", id] as const,
search: (query: string) => ["messages-search", query] as const,
};
type MessagePage = { data: MessageRecord[]; nextCursor: string | null };
/**
* Single source of truth for the paginated message list. Both useMessages and
* useMessagesHasMore derive from this one SWR key, so the cursor probe no
* longer triggers a duplicate API call.
*/
function useMessagesPage(guildId: string, channelId?: string) {
const key = guildId ? msgKeys.list(guildId, channelId) : null;
return useSWR<MessagePage>(key, () =>
messagesApi.list(guildId, 50, channelId || undefined),
);
}
// ── Messages list (paginated, cursor-based) ──────
export function useMessages(guildId: string, channelId?: string) {
return useQuery<MessageRecord[]>({
queryKey: msgKeys.list(guildId, channelId),
queryFn: async () => {
const result = await messagesApi.list(
guildId,
50,
channelId || undefined,
);
return result.data;
},
enabled: !!guildId,
});
const page = useMessagesPage(guildId, channelId);
return {
...page,
data: page.data?.data,
refetch: () => page.mutate(),
};
}
export function useMessagesHasMore(guildId: string, channelId?: string) {
return useQuery({
queryKey: [...msgKeys.list(guildId, channelId), "cursor"],
queryFn: async () => {
const result = await messagesApi.list(
guildId,
50,
channelId || undefined,
);
return { cursor: result.nextCursor, hasMore: result.nextCursor !== null };
const page = useMessagesPage(guildId, channelId);
return {
data: {
cursor: page.data?.nextCursor ?? null,
hasMore: page.data ? page.data.nextCursor !== null : undefined,
},
enabled: !!guildId,
});
};
}
export function useLoadMore() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
const { mutate } = useSWRConfig();
return useAction(
async ({
guildId,
channelId,
cursor,
@@ -66,76 +70,73 @@ export function useLoadMore() {
channelId || undefined,
cursor,
);
return { data: result.data, cursor: result.nextCursor };
},
onSuccess: (data, vars) => {
const key = msgKeys.list(vars.guildId, vars.channelId);
qc.setQueryData<MessageRecord[]>(key, (old) =>
old ? [...old, ...data.data] : data.data,
const key = msgKeys.list(guildId, channelId);
await mutate(
key,
(old: MessagePage | undefined): MessagePage | undefined =>
old
? {
data: [...old.data, ...result.data],
nextCursor: result.nextCursor,
}
: result,
{ revalidate: false },
);
qc.setQueryData([...key, "cursor"], {
cursor: data.cursor,
hasMore: data.cursor !== null,
});
return result;
},
});
);
}
// ── Channels list ────────────────────────────────
export function useTextChannels(guildId: string) {
return useQuery<Channel[]>({
queryKey: ["text-channels", guildId],
queryFn: () => voiceApi.getTextChannels(guildId),
enabled: !!guildId,
});
return useSWR<Channel[]>(guildId ? ["text-channels", guildId] : null, () =>
voiceApi.getTextChannels(guildId),
);
}
// ── Images ───────────────────────────────────────
export function useImages(guildId: string) {
return useQuery<MessageRecord[]>({
queryKey: msgKeys.images(guildId),
queryFn: async () => {
return useSWR<MessageRecord[]>(
guildId ? msgKeys.images(guildId) : null,
async () => {
const result = await messagesApi.getImages(guildId, 50);
return result.data;
},
enabled: !!guildId,
});
);
}
// ── Review ───────────────────────────────────────
export function useReview(channelId?: string) {
return useQuery<MessageRecord[]>({
queryKey: msgKeys.review(channelId),
queryFn: async () => {
return useSWR<MessageRecord[]>(
msgKeys.review(channelId),
async () => {
const result = await messagesApi.getReview(50, channelId || undefined);
return result.results;
},
});
{
refreshInterval: 15_000,
},
);
}
// ── Detail ───────────────────────────────────────
export function useMessageDetail(id: string | null) {
const detail = useQuery<MessageRecord>({
queryKey: msgKeys.detail(id ?? ""),
queryFn: () => messagesApi.getDetail(id!),
enabled: !!id,
});
const attachments = useQuery<AttachmentRecord[]>({
queryKey: [...msgKeys.detail(id ?? ""), "attachments"],
queryFn: async () => {
if (!id) return [];
const res = await messagesApi.getAttachments(
detail.data?.channel_id ?? "",
10,
);
const detail = useSWR<MessageRecord>(id ? msgKeys.detail(id) : null, () =>
messagesApi.getDetail(id!),
);
const attachments = useSWR<AttachmentRecord[]>(
id && detail.data?.channel_id
? [...msgKeys.detail(id), "attachments"]
: null,
async () => {
const res = await messagesApi.getAttachments(detail.data!.channel_id, 10);
return res.data;
},
enabled: !!id && !!detail.data?.channel_id,
});
);
return {
message: detail.data ?? null,
attachments: attachments.data ?? [],
@@ -147,52 +148,70 @@ export function useMessageDetail(id: string | null) {
// ── Mutations ────────────────────────────────────
export function useReanalyze() {
const _qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => messagesApi.reanalyze(id),
});
return useAction((id: string) => messagesApi.reanalyze(id));
}
export function useReanalyzeBatch() {
return useMutation({
mutationFn: (guildId: string) => messagesApi.reanalyzeBatch(guildId),
});
return useAction((guildId: string) => messagesApi.reanalyzeBatch(guildId));
}
// ── Search ───────────────────────────────────────
export function useMessageSearch(query: string, enabled: boolean) {
return useSWR<MessageRecord[]>(
enabled && query.trim().length >= 2 ? msgKeys.search(query) : null,
async () => {
const res = await messagesApi.search(query, 50);
return res.results;
},
);
}
// ── WS sync helpers ──────────────────────────────
export function useMessagesWsSync(ws: WsHook, guildId: string) {
const qc = useQueryClient();
const { mutate } = useSWRConfig();
useEffect(() => {
if (!guildId) return;
const key = msgKeys.list(guildId);
const unsub1 = ws.on("message_created", (data) => {
qc.setQueryData<MessageRecord[]>(key, (old) =>
old ? [data as MessageRecord, ...old] : [data as MessageRecord],
// Patch every message-list key for this guild (all channels + "__all__")
const patchLists = (
updater: (old: MessagePage | undefined) => MessagePage | undefined,
) => {
void mutate(
(key) =>
Array.isArray(key) && key[0] === "messages" && key[1] === guildId,
updater,
{ revalidate: false },
);
};
const unsub1 = ws.on("message_created", (data) => {
const msg = data as MessageRecord;
patchLists((old) => (old ? { ...old, data: [msg, ...old.data] } : old));
});
const unsub2 = ws.on("message_updated", (data) => {
qc.setQueryData<MessageRecord[]>(key, (old) =>
const msg = data as MessageRecord;
patchLists((old) =>
old
? old.map((m) =>
m.id === (data as MessageRecord).id ? (data as MessageRecord) : m,
)
? { ...old, data: old.data.map((m) => (m.id === msg.id ? msg : m)) }
: old,
);
void mutate(msgKeys.detail(msg.id), msg, { revalidate: false });
});
const unsub3 = ws.on("message_deleted", (data) => {
qc.setQueryData<MessageRecord[]>(key, (old) =>
old ? old.filter((m) => m.id !== (data as { id: string }).id) : old,
const { id } = data as { id: string };
patchLists((old) =>
old ? { ...old, data: old.data.filter((m) => m.id !== id) } : old,
);
});
const unsub4 = ws.on("message_analyzed", (data) => {
qc.setQueryData<MessageRecord[]>(key, (old) =>
const msg = data as MessageRecord;
patchLists((old) =>
old
? old.map((m) =>
m.id === (data as MessageRecord).id ? (data as MessageRecord) : m,
)
? { ...old, data: old.data.map((m) => (m.id === msg.id ? msg : m)) }
: old,
);
void mutate(msgKeys.detail(msg.id), msg, { revalidate: false });
});
return () => {
unsub1();
@@ -200,5 +219,5 @@ export function useMessagesWsSync(ws: WsHook, guildId: string) {
unsub3();
unsub4();
};
}, [ws, guildId, qc]);
}, [ws, guildId, mutate]);
}