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
+1
View File
@@ -19,6 +19,7 @@ export {
useImages,
useLoadMore,
useMessageDetail,
useMessageSearch,
useMessages,
useMessagesHasMore,
useMessagesWsSync,
+55
View File
@@ -0,0 +1,55 @@
import { useCallback, useRef, useState } from "react";
export interface UseActionState {
isPending: boolean;
error: Error | null;
}
/**
* A lightweight mutation hook with a TanStack-compatible surface
* ({ mutate, mutateAsync, isPending, error }) built on plain state —
* the SWR replacement for useMutation. Fire-and-forget via `mutate`,
* await the result via `mutateAsync`.
*
* `onSuccess` receives (data, args) and may perform SWR cache updates
* (e.g. `mutate(key, data, { revalidate: false })`).
*/
export function useAction<TArgs = void, TResult = unknown>(
fn: (args: TArgs) => Promise<TResult>,
options?: {
onSuccess?: (data: TResult, args: TArgs) => void | Promise<void>;
},
) {
const [state, setState] = useState<UseActionState>({
isPending: false,
error: null,
});
const fnRef = useRef(fn);
fnRef.current = fn;
const onSuccessRef = useRef(options?.onSuccess);
onSuccessRef.current = options?.onSuccess;
const run = useCallback(async (args?: TArgs): Promise<TResult> => {
setState({ isPending: true, error: null });
try {
const data = await fnRef.current(args as TArgs);
await onSuccessRef.current?.(data, args as TArgs);
setState({ isPending: false, error: null });
return data;
} catch (err) {
setState({ isPending: false, error: err as Error });
throw err;
}
}, []);
return {
mutate: (args?: TArgs) => {
void run(args);
},
mutateAsync: run,
isPending: state.isPending,
error: state.error,
reset: () => setState({ isPending: false, error: null }),
};
}
+3 -5
View File
@@ -1,4 +1,4 @@
import { useQuery } from "@tanstack/react-query";
import useSWR from "swr";
import { configApi } from "@/lib/api";
import type { AppConfig } from "@/lib/types";
@@ -7,9 +7,7 @@ import type { AppConfig } from "@/lib/types";
* Fetch the app configuration from the backend.
*/
export function useConfig() {
return useQuery<AppConfig>({
queryKey: ["config"],
queryFn: () => configApi.get(),
staleTime: 120_000,
return useSWR<AppConfig>(["config"], () => configApi.get(), {
dedupingInterval: 120_000,
});
}
+36 -25
View File
@@ -1,4 +1,4 @@
import { useQuery } from "@tanstack/react-query";
import useSWR from "swr";
import { dashboardApi } from "@/lib/api";
import type {
@@ -8,40 +8,51 @@ import type {
} from "@/lib/types";
export function useStats() {
return useQuery<DashboardStats>({
queryKey: ["dashboard-stats"],
queryFn: () => dashboardApi.getStats(),
});
return useSWR<DashboardStats>(["dashboard-stats"], () =>
dashboardApi.getStats(),
);
}
export function useUsers(search?: string) {
return useQuery({
queryKey: ["dashboard-users", search ?? ""],
queryFn: () => dashboardApi.listUsers(20, undefined, search),
select: (data) => data.data,
});
return useSWR(
["dashboard-users", search ?? ""],
async () => {
const res = await dashboardApi.listUsers(20, undefined, search);
return res.data;
},
{
keepPreviousData: true,
},
);
}
export function useChannels(guildId?: string, search?: string) {
return useQuery({
queryKey: ["dashboard-channels", guildId ?? "__all__", search ?? ""],
queryFn: () => dashboardApi.listChannels(20, search, guildId || undefined),
select: (data) => data.data,
});
return useSWR(
["dashboard-channels", guildId ?? "__all__", search ?? ""],
async () => {
const res = await dashboardApi.listChannels(
20,
search,
guildId || undefined,
);
return res.data;
},
{
keepPreviousData: true,
},
);
}
export function useUserDetail(userId: string | null) {
return useQuery<DashboardUserDetail>({
queryKey: ["dashboard-user", userId],
queryFn: () => dashboardApi.getUserDetail(userId!),
enabled: !!userId,
});
return useSWR<DashboardUserDetail>(
userId ? ["dashboard-user", userId] : null,
() => dashboardApi.getUserDetail(userId!),
);
}
export function useChannelDetail(channelId: string | null) {
return useQuery<DashboardChannelDetail>({
queryKey: ["dashboard-channel", channelId],
queryFn: () => dashboardApi.getChannelDetail(channelId!),
enabled: !!channelId,
});
return useSWR<DashboardChannelDetail>(
channelId ? ["dashboard-channel", channelId] : null,
() => dashboardApi.getChannelDetail(channelId!),
);
}
+3 -5
View File
@@ -1,4 +1,4 @@
import { useQuery } from "@tanstack/react-query";
import useSWR from "swr";
import { voiceApi } from "@/lib/api";
import type { Guild } from "@/lib/types";
@@ -7,9 +7,7 @@ import type { Guild } from "@/lib/types";
* Fetch the list of available Discord guilds.
*/
export function useGuilds() {
return useQuery<Guild[]>({
queryKey: ["guilds"],
queryFn: () => voiceApi.getGuilds(),
staleTime: 60_000,
return useSWR<Guild[]>(["guilds"], () => voiceApi.getGuilds(), {
dedupingInterval: 60_000,
});
}
+23 -30
View File
@@ -1,58 +1,51 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { mediaApi } from "@/lib/api";
import type { MediaState } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook";
const MEDIA_KEY = ["media-state"] as const;
export function useMediaState() {
return useQuery<MediaState>({
queryKey: ["media-state"],
queryFn: () => mediaApi.getStatus(),
retry: false,
refetchInterval: 10_000,
return useSWR<MediaState>(MEDIA_KEY, () => mediaApi.getStatus(), {
refreshInterval: 10_000,
shouldRetryOnError: false,
});
}
function useMediaAction<TArgs>(fn: (args: TArgs) => Promise<MediaState>) {
const { mutate } = useSWRConfig();
return useAction(fn, {
onSuccess: (data) => {
void mutate(MEDIA_KEY, data, { revalidate: false });
},
});
}
export function useMediaQueue() {
const qc = useQueryClient();
return useMutation({
mutationFn: (url: string) => mediaApi.queue(url, "music"),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
return useMediaAction((url: string) => mediaApi.queue(url, "music"));
}
export function useMediaSkip() {
const qc = useQueryClient();
return useMutation({
mutationFn: () => mediaApi.skip(),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
return useMediaAction(() => mediaApi.skip());
}
export function useMediaStop() {
const qc = useQueryClient();
return useMutation({
mutationFn: () => mediaApi.stop(),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
return useMediaAction(() => mediaApi.stop());
}
export function useMediaVolume() {
const qc = useQueryClient();
return useMutation({
mutationFn: (volume: number) => mediaApi.volume(volume),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
return useMediaAction((volume: number) => mediaApi.volume(volume));
}
/** Subscribe to WS media_state events to keep cache fresh */
export function useMediaWsSync(ws: WsHook) {
const qc = useQueryClient();
const { mutate } = useSWRConfig();
useEffect(() => {
const unsub = ws.on("media_state", (data) => {
qc.setQueryData(["media-state"], data as MediaState);
void mutate(MEDIA_KEY, data as MediaState, { revalidate: false });
});
return unsub;
}, [ws, qc]);
}, [ws, mutate]);
}
+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]);
}
+18 -16
View File
@@ -1,37 +1,39 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { recordingsApi } from "@/lib/api";
import type { VoiceRecording } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook";
const RECORDINGS_KEY = ["recordings"] as const;
export function useRecordings() {
return useQuery<VoiceRecording[]>({
queryKey: ["recordings"],
queryFn: async () => {
const res = await recordingsApi.list(50);
return res.items;
},
return useSWR<VoiceRecording[]>(RECORDINGS_KEY, async () => {
const res = await recordingsApi.list(50);
return res.items;
});
}
export function useDeleteRecording() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => recordingsApi.delete(id),
onSuccess: () => qc.invalidateQueries({ queryKey: ["recordings"] }),
const { mutate } = useSWRConfig();
return useAction((id: string) => recordingsApi.delete(id), {
onSuccess: () => {
void mutate(RECORDINGS_KEY);
},
});
}
export function useRecordingsWsSync(ws: WsHook) {
const qc = useQueryClient();
const { mutate } = useSWRConfig();
useEffect(() => {
const unsub = ws.on("voice_recording_uploaded", (data) => {
const rec = data as VoiceRecording;
qc.setQueryData<VoiceRecording[]>(["recordings"], (old) =>
old ? [rec, ...old] : [rec],
void mutate(
RECORDINGS_KEY,
(old: VoiceRecording[] | undefined) => (old ? [rec, ...old] : [rec]),
{ revalidate: false },
);
});
return unsub;
}, [ws, qc]);
}, [ws, mutate]);
}
+29 -33
View File
@@ -1,24 +1,22 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useState } from "react";
import useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { voiceApi } from "@/lib/api";
import type { ActiveSpeaker, Channel, VoiceStatus } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook";
const STATUS_KEY = ["voice-status"] as const;
export function useVoiceStatus() {
return useQuery<VoiceStatus>({
queryKey: ["voice-status"],
queryFn: () => voiceApi.getStatus(),
retry: false,
return useSWR<VoiceStatus>(STATUS_KEY, () => voiceApi.getStatus(), {
shouldRetryOnError: false,
});
}
export function useVoiceChannels(guildId: string) {
return useQuery<Channel[]>({
queryKey: ["voice-channels", guildId],
queryFn: () => voiceApi.getVoiceChannels(guildId),
enabled: !!guildId,
});
return useSWR<Channel[]>(guildId ? ["voice-channels", guildId] : null, () =>
voiceApi.getVoiceChannels(guildId),
);
}
export function useSpeakers() {
@@ -46,33 +44,31 @@ export function useSpeakers() {
return { speakers, subscribe };
}
function useStatusInvalidator() {
const { mutate } = useSWRConfig();
return () => {
void mutate(STATUS_KEY);
};
}
export function useVoiceConnect() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({
guildId,
channelId,
}: {
guildId: string;
channelId: string;
}) => voiceApi.connect(guildId, channelId),
onSuccess: () => qc.invalidateQueries({ queryKey: ["voice-status"] }),
});
const invalidate = useStatusInvalidator();
return useAction(
({ guildId, channelId }: { guildId: string; channelId: string }) =>
voiceApi.connect(guildId, channelId),
{ onSuccess: invalidate },
);
}
export function useVoiceDisconnect() {
const qc = useQueryClient();
return useMutation({
mutationFn: () => voiceApi.disconnect(),
onSuccess: () => qc.invalidateQueries({ queryKey: ["voice-status"] }),
});
const invalidate = useStatusInvalidator();
return useAction(() => voiceApi.disconnect(), { onSuccess: invalidate });
}
export function useMicTransmit() {
return useMutation({
mutationFn: (active: boolean) =>
voiceApi.sendCommand(
active ? "voice:transmit:start" : "voice:transmit:stop",
),
});
return useAction((active: boolean) =>
voiceApi.sendCommand(
active ? "voice:transmit:start" : "voice:transmit:stop",
),
);
}