Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(dashboard): migrate all pages from manual fetch to React Query

rmyndharise1ef5dd5486b
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index bc0f708c7..21c674922 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -1,5 +1,6 @@
import { useState, useEffect, lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Loader2 } from 'lucide-react';
import { Layout } from './components/Layout';
import { ToastProvider } from './components/Toast';
@@ -17,6 +18,16 @@ const MessageTester = lazy(() => import('./pages/MessageTester').then(m => ({ de
const Infrastructure = lazy(() => import('./pages/Infrastructure').then(m => ({ default: m.Infrastructure })));
const Plugins = lazy(() => import('./pages/Plugins'));
+const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ staleTime: 30_000,
+ retry: 1,
+ refetchOnWindowFocus: true,
+ },
+ },
+});
+
function AppContent() {
// Initialize from sessionStorage to avoid setState in effect
const savedKey = sessionStorage.getItem('openwa_api_key');
@@ -108,9 +119,11 @@ function AppContent() {
function App() {
return (
<ErrorBoundary>
- <RoleProvider>
- <AppContent />
- </RoleProvider>
+ <QueryClientProvider client={queryClient}>
+ <RoleProvider>
+ <AppContent />
+ </RoleProvider>
+ </QueryClientProvider>
</ErrorBoundary>
);
}
diff --git a/dashboard/src/hooks/queries.ts b/dashboard/src/hooks/queries.ts
new file mode 100644
index 000000000..21e641b66
--- /dev/null
+++ b/dashboard/src/hooks/queries.ts
@@ -0,0 +1,230 @@
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
+import {
+ sessionApi,
+ webhookApi,
+ apiKeyApi,
+ auditApi,
+ infraApi,
+ pluginsApi,
+ type Webhook,
+} from '../services/api';
+
+// ── Query Keys ────────────────────────────────────────────────────────
+
+export const queryKeys = {
+ sessions: ['sessions'] as const,
+ sessionStats: ['sessions', 'stats'] as const,
+ sessionGroups: (sessionId: string) => ['sessions', sessionId, 'groups'] as const,
+ webhooks: ['webhooks'] as const,
+ apiKeys: ['apiKeys'] as const,
+ logs: (params: { severity?: string; page: number; limit: number }) =>
+ ['logs', params] as const,
+ infraStatus: ['infra', 'status'] as const,
+ plugins: ['plugins'] as const,
+ engines: ['engines'] as const,
+ currentEngine: ['engines', 'current'] as const,
+};
+
+// ── Session Queries ───────────────────────────────────────────────────
+
+export function useSessionsQuery() {
+ return useQuery({
+ queryKey: queryKeys.sessions,
+ queryFn: sessionApi.list,
+ staleTime: 30_000,
+ });
+}
+
+export function useSessionStatsQuery() {
+ return useQuery({
+ queryKey: queryKeys.sessionStats,
+ queryFn: sessionApi.getStats,
+ staleTime: 30_000,
+ });
+}
+
+export function useSessionGroupsQuery(sessionId: string, enabled: boolean) {
+ return useQuery({
+ queryKey: queryKeys.sessionGroups(sessionId),
+ queryFn: () => sessionApi.getGroups(sessionId),
+ enabled: enabled && !!sessionId,
+ staleTime: 60_000,
+ });
+}
+
+export function useCreateSessionMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (name: string) => sessionApi.create(name),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.sessions });
+ void queryClient.invalidateQueries({ queryKey: queryKeys.sessionStats });
+ },
+ });
+}
+
+export function useDeleteSessionMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => sessionApi.delete(id),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.sessions });
+ void queryClient.invalidateQueries({ queryKey: queryKeys.sessionStats });
+ },
+ });
+}
+
+export function useStartSessionMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => sessionApi.start(id),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.sessions });
+ },
+ });
+}
+
+export function useStopSessionMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => sessionApi.stop(id),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.sessions });
+ },
+ });
+}
+
+// ── Webhook Queries ───────────────────────────────────────────────────
+
+export function useWebhooksQuery() {
+ return useQuery({
+ queryKey: queryKeys.webhooks,
+ queryFn: webhookApi.listAll,
+ staleTime: 30_000,
+ });
+}
+
+export function useCreateWebhookMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (params: { sessionId: string; url: string; events: string[] }) =>
+ webhookApi.create(params.sessionId, { url: params.url, events: params.events }),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.webhooks });
+ },
+ });
+}
+
+export function useUpdateWebhookMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (params: { sessionId: string; id: string; data: Partial<Webhook> }) =>
+ webhookApi.update(params.sessionId, params.id, params.data),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.webhooks });
+ },
+ });
+}
+
+export function useDeleteWebhookMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (params: { sessionId: string; id: string }) =>
+ webhookApi.delete(params.sessionId, params.id),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.webhooks });
+ },
+ });
+}
+
+// ── API Key Queries ───────────────────────────────────────────────────
+
+export function useApiKeysQuery() {
+ return useQuery({
+ queryKey: queryKeys.apiKeys,
+ queryFn: apiKeyApi.list,
+ staleTime: 30_000,
+ });
+}
+
+export function useCreateApiKeyMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (data: { name: string; role: string; allowedIps?: string[]; allowedSessions?: string[]; expiresAt?: string }) =>
+ apiKeyApi.create(data),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.apiKeys });
+ },
+ });
+}
+
+export function useDeleteApiKeyMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => apiKeyApi.delete(id),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.apiKeys });
+ },
+ });
+}
+
+export function useRevokeApiKeyMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => apiKeyApi.revoke(id),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.apiKeys });
+ },
+ });
+}
+
+// ── Logs Queries ──────────────────────────────────────────────────────
+
+export function useLogsQuery(params: { severity?: string; page: number; limit: number }) {
+ return useQuery({
+ queryKey: queryKeys.logs(params),
+ queryFn: () =>
+ auditApi.list({
+ severity: params.severity,
+ limit: params.limit,
+ offset: (params.page - 1) * params.limit,
+ }),
+ staleTime: 15_000,
+ });
+}
+
+// ── Infrastructure Queries ────────────────────────────────────────────
+
+export function useInfraStatusQuery() {
+ return useQuery({
+ queryKey: queryKeys.infraStatus,
+ queryFn: infraApi.getStatus,
+ staleTime: 30_000,
+ });
+}
+
+// ── Plugin Queries ────────────────────────────────────────────────────
+
+export function usePluginsQuery() {
+ return useQuery({
+ queryKey: queryKeys.plugins,
+ queryFn: pluginsApi.list,
+ staleTime: 30_000,
+ });
+}
+
+export function useEnginesQuery() {
+ return useQuery({
+ queryKey: queryKeys.engines,
+ queryFn: pluginsApi.getEngines,
+ staleTime: 60_000,
+ });
+}
+
+export function useCurrentEngineQuery() {
+ return useQuery({
+ queryKey: queryKeys.currentEngine,
+ queryFn: pluginsApi.getCurrentEngine,
+ staleTime: 60_000,
+ });
+}
diff --git a/dashboard/src/pages/ApiKeys.tsx b/dashboard/src/pages/ApiKeys.tsx
index 14a50e851..a140f4e8c 100644
--- a/dashboard/src/pages/ApiKeys.tsx
+++ b/dashboard/src/pages/ApiKeys.tsx
@@ -7,8 +7,9 @@ import {
type VisibilityState,
} from '@tanstack/react-table';
import { Plus, Copy, RefreshCw, Trash2, Eye, EyeOff, Loader2, X, Check, KeyRound, AlertTriangle } from 'lucide-react';
-import { apiKeyApi, type ApiKey } from '../services/api';
+import type { ApiKey } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
+import { useApiKeysQuery, useCreateApiKeyMutation, useDeleteApiKeyMutation, useRevokeApiKeyMutation } from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
import './ApiKeys.css';
@@ -35,9 +36,10 @@ const columnHelper = createColumnHelper<ApiKey>();
export function ApiKeys() {
useDocumentTitle('API Keys');
- const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
- const [loading, setLoading] = useState(true);
- const [_error, setError] = useState<string | null>(null);
+ const { data: apiKeys = [], isLoading: loading } = useApiKeysQuery();
+ const createMutation = useCreateApiKeyMutation();
+ const deleteMutation = useDeleteApiKeyMutation();
+ const revokeMutation = useRevokeApiKeyMutation();
const [visibleKeys, setVisibleKeys] = useState<Set<string>>(new Set());
const [showModal, setShowModal] = useState(false);
const [newKey, setNewKey] = useState({ name: '', role: 'operator' });
@@ -61,28 +63,10 @@ export function ApiKeys() {
});
}, [isMobile, isSmall]);
- useEffect(() => {
- fetchKeys();
- }, []);
-
- const fetchKeys = async () => {
- try {
- setLoading(true);
- const data = await apiKeyApi.list();
- setApiKeys(data);
- } catch (err) {
- console.error('Failed to fetch API keys:', err);
- setError(err instanceof Error ? err.message : 'Failed to load API keys');
- } finally {
- setLoading(false);
- }
- };
-
const handleCreate = async () => {
if (!newKey.name) return;
try {
- const created = await apiKeyApi.create({ name: newKey.name, role: newKey.role });
- setApiKeys([...apiKeys, created]);
+ const created = await createMutation.mutateAsync({ name: newKey.name, role: newKey.role });
setCreatedKey(created.apiKey || null);
setNewKey({ name: '', role: 'operator' });
} catch (err) {
@@ -92,8 +76,7 @@ export function ApiKeys() {
const handleRevoke = async (id: string) => {
try {
- await apiKeyApi.revoke(id);
- setApiKeys(apiKeys.map(k => (k.id === id ? { ...k, isActive: false } : k)));
+ await revokeMutation.mutateAsync(id);
} catch (err) {
console.error('Failed to revoke:', err);
}
@@ -101,8 +84,7 @@ export function ApiKeys() {
const handleDelete = async (id: string) => {
try {
- await apiKeyApi.delete(id);
- setApiKeys(apiKeys.filter(k => k.id !== id));
+ await deleteMutation.mutateAsync(id);
} catch (err) {
console.error('Failed to delete:', err);
}
diff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsx
index 1fe8c3baa..04027772a 100644
--- a/dashboard/src/pages/Dashboard.tsx
+++ b/dashboard/src/pages/Dashboard.tsx
@@ -1,45 +1,24 @@
-import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { MessageSquare, Send, Webhook, Activity, ArrowUpRight, ArrowDownRight, Loader2 } from 'lucide-react';
-import { sessionApi, webhookApi, type Session, type SessionStats } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
+import { useSessionsQuery, useSessionStatsQuery, useWebhooksQuery, useStopSessionMutation } from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
import './Dashboard.css';
export function Dashboard() {
useDocumentTitle('Dashboard');
const navigate = useNavigate();
- const [sessions, setSessions] = useState<Session[]>([]);
- const [stats, setStats] = useState<SessionStats | null>(null);
- const [webhookCount, setWebhookCount] = useState(0);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
-
- useEffect(() => {
- async function fetchData() {
- try {
- setLoading(true);
- const [sessionsData, statsData, webhooksData] = await Promise.all([
- sessionApi.list(),
- sessionApi.getStats(),
- webhookApi.listAll().catch(() => []),
- ]);
- setSessions(sessionsData);
- setStats(statsData);
- setWebhookCount(webhooksData.length);
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to load data');
- } finally {
- setLoading(false);
- }
- }
- fetchData();
- }, []);
+ const { data: sessions = [], isLoading: loadingSessions, error: sessionsError } = useSessionsQuery();
+ const { data: stats } = useSessionStatsQuery();
+ const { data: webhooks = [] } = useWebhooksQuery();
+ const stopMutation = useStopSessionMutation();
+ const loading = loadingSessions;
+ const error = sessionsError instanceof Error ? sessionsError.message : sessionsError ? 'Failed to load data' : null;
+ const webhookCount = webhooks.length;
const handleDisconnect = async (id: string) => {
try {
- await sessionApi.stop(id);
- setSessions(sessions.map(s => (s.id === id ? { ...s, status: 'disconnected' } : s)));
+ await stopMutation.mutateAsync(id);
} catch (err) {
console.error('Failed to disconnect:', err);
}
diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsx
index 175be4a82..59f42b848 100644
--- a/dashboard/src/pages/Infrastructure.tsx
+++ b/dashboard/src/pages/Infrastructure.tsx
@@ -14,6 +14,7 @@ import {
} from 'lucide-react';
import { infraApi } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
+import { useInfraStatusQuery } from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
import { useToast } from '../components/Toast';
import './Infrastructure.css';
@@ -85,7 +86,7 @@ interface RateLimitConfig {
export function Infrastructure() {
useDocumentTitle('Infrastructure');
const toast = useToast();
- const [loading, setLoading] = useState(true);
+ const { data: infraStatus, isLoading: loading } = useInfraStatusQuery();
const [saving, setSaving] = useState(false);
const [showRestartModal, setShowRestartModal] = useState(false);
const [restartCountdown, setRestartCountdown] = useState(0);
@@ -153,46 +154,35 @@ export function Infrastructure() {
max: 100,
});
- // Fetch infrastructure status from API
+ // Populate config state from infra status query data
useEffect(() => {
- const fetchInfraStatus = async () => {
- try {
- const status = await infraApi.getStatus();
-
- // Update configs with real data
- setDbConfig(prev => ({
- ...prev,
- type: (status.database.type as 'sqlite' | 'postgres') || 'sqlite',
- host: status.database.host || 'localhost',
- }));
-
- setRedisConfig(prev => ({
- ...prev,
- host: status.redis.host,
- port: String(status.redis.port),
- connected: status.redis.connected,
- }));
-
- setStorageConfig(prev => ({
- ...prev,
- type: status.storage.type,
- localPath: status.storage.path || './uploads',
- }));
-
- setQueueEnabled(status.queue.enabled);
- setQueueStats({
- messages: status.queue.messages,
- webhooks: status.queue.webhooks,
- });
- } catch (err) {
- console.error('Failed to fetch infra status:', err);
- } finally {
- setLoading(false);
- }
- };
-
- fetchInfraStatus();
- }, []);
+ if (!infraStatus) return;
+
+ setDbConfig(prev => ({
+ ...prev,
+ type: (infraStatus.database.type as 'sqlite' | 'postgres') || 'sqlite',
+ host: infraStatus.database.host || 'localhost',
+ }));
+
+ setRedisConfig(prev => ({
+ ...prev,
+ host: infraStatus.redis.host,
+ port: String(infraStatus.redis.port),
+ connected: infraStatus.redis.connected,
+ }));
+
+ setStorageConfig(prev => ({
+ ...prev,
+ type: infraStatus.storage.type,
+ localPath: infraStatus.storage.path || './uploads',
+ }));
+
+ setQueueEnabled(infraStatus.queue.enabled);
+ setQueueStats({
+ messages: infraStatus.queue.messages,
+ webhooks: infraStatus.queue.webhooks,
+ });
+ }, [infraStatus]);
// Show loading state
if (loading) {
diff --git a/dashboard/src/pages/Logs.tsx b/dashboard/src/pages/Logs.tsx
index e3030211c..3a8ea0207 100644
--- a/dashboard/src/pages/Logs.tsx
+++ b/dashboard/src/pages/Logs.tsx
@@ -1,43 +1,22 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useState } from 'react';
import { Download, Search, Filter, Loader2, FileText } from 'lucide-react';
-import { auditApi, type AuditLog } from '../services/api';
+import type { AuditLog } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
+import { useLogsQuery } from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
import './Logs.css';
export function Logs() {
useDocumentTitle('Audit Logs');
- const [logs, setLogs] = useState<AuditLog[]>([]);
- const [total, setTotal] = useState(0);
- const [loading, setLoading] = useState(true);
- const [_error, setError] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState('');
const [severityFilter, setSeverityFilter] = useState('all');
const [page, setPage] = useState(1);
const limit = 20;
- const fetchLogs = useCallback(async () => {
- try {
- setLoading(true);
- const params: { severity?: string; limit: number; offset: number } = {
- limit,
- offset: (page - 1) * limit,
- };
- if (severityFilter !== 'all') params.severity = severityFilter;
- const result = await auditApi.list(params);
- setLogs(result.data);
- setTotal(result.total);
- } catch (err) {
- console.error('Failed to fetch logs:', err);
- setError(err instanceof Error ? err.message : 'Failed to load logs');
- } finally {
- setLoading(false);
- }
- }, [severityFilter, page, limit]);
-
- useEffect(() => {
- fetchLogs();
- }, [fetchLogs]);
+ const severityParam = severityFilter !== 'all' ? severityFilter : undefined;
+ const { data, isLoading: loading } = useLogsQuery({ severity: severityParam, page, limit });
+ const logs: AuditLog[] = data?.data ?? [];
+ const total: number = data?.total ?? 0;
const filteredLogs = logs.filter(log => {
const matchesSearch =
diff --git a/dashboard/src/pages/MessageTester.tsx b/dashboard/src/pages/MessageTester.tsx
index 09fb8d418..17d0c291d 100644
--- a/dashboard/src/pages/MessageTester.tsx
+++ b/dashboard/src/pages/MessageTester.tsx
@@ -1,8 +1,9 @@
import { useState, useEffect } from 'react';
import { Send, CheckCircle, XCircle, Loader2 } from 'lucide-react';
-import { sessionApi, messageApi, type Session } from '../services/api';
+import { messageApi } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useRole } from '../hooks/useRole';
+import { useSessionsQuery, useSessionGroupsQuery } from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
import './MessageTester.css';
@@ -13,66 +14,42 @@ interface ApiResponse {
error?: string;
}
-interface Group {
- id: string;
- name: string;
-}
-
export function MessageTester() {
useDocumentTitle('Message Tester');
const { canWrite } = useRole();
- const [sessions, setSessions] = useState<Session[]>([]);
+ const { data: allSessions = [], isLoading: loadingSessions } = useSessionsQuery();
+ const sessions = allSessions.filter(s => s.status === 'ready');
const [session, setSession] = useState('');
const [recipient, setRecipient] = useState('');
const [recipientType, setRecipientType] = useState<'personal' | 'group'>('personal');
- const [groups, setGroups] = useState<Group[]>([]);
const [selectedGroup, setSelectedGroup] = useState('');
- const [loadingGroups, setLoadingGroups] = useState(false);
const [messageType, setMessageType] = useState<'text' | 'image' | 'video' | 'audio' | 'document'>('text');
const [content, setContent] = useState('');
const [mediaUrl, setMediaUrl] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [response, setResponse] = useState<ApiResponse | null>(null);
- const [loadingSessions, setLoadingSessions] = useState(true);
+ const { data: groups = [], isLoading: loadingGroups } = useSessionGroupsQuery(
+ session,
+ recipientType === 'group',
+ );
+
+ // Auto-select first session
useEffect(() => {
- async function fetchSessions() {
- try {
- const data = await sessionApi.list();
- const readySessions = data.filter(s => s.status === 'ready');
- setSessions(readySessions);
- if (readySessions.length > 0) setSession(readySessions[0].id);
- } catch (err) {
- console.error('Failed to fetch sessions:', err);
- } finally {
- setLoadingSessions(false);
- }
+ if (sessions.length > 0 && !session) {
+ setSession(sessions[0].id);
}
- fetchSessions();
- }, []);
+ }, [sessions, session]);
- // Fetch groups when session changes and recipientType is group
+ // Auto-select first group
useEffect(() => {
- if (!session || recipientType !== 'group') {
- setGroups([]);
- setSelectedGroup('');
- return;
+ if (groups.length > 0 && !selectedGroup) {
+ setSelectedGroup(groups[0].id);
}
-
- async function fetchGroups() {
- setLoadingGroups(true);
- try {
- const groupList = await sessionApi.getGroups(session);
- setGroups(groupList);
- if (groupList.length > 0) setSelectedGroup(groupList[0].id);
- } catch {
- setGroups([]);
- } finally {
- setLoadingGroups(false);
- }
+ if (recipientType !== 'group') {
+ setSelectedGroup('');
}
- fetchGroups();
- }, [session, recipientType]);
+ }, [groups, selectedGroup, recipientType]);
const handleSend = async () => {
// For groups, use selectedGroup; for personal, use recipient
diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsx
index 84c3f6266..fd5341c45 100644
--- a/dashboard/src/pages/Plugins.tsx
+++ b/dashboard/src/pages/Plugins.tsx
@@ -1,4 +1,5 @@
-import { useState, useEffect } from 'react';
+import { useState } from 'react';
+import { useQueryClient } from '@tanstack/react-query';
import {
Puzzle,
Power,
@@ -15,9 +16,16 @@ import {
Zap,
X,
} from 'lucide-react';
-import { pluginsApi, infraApi } from '../services/api';
-import type { Plugin, Engine } from '../services/api';
+import { pluginsApi } from '../services/api';
+import type { Plugin } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
+import {
+ usePluginsQuery,
+ useEnginesQuery,
+ useCurrentEngineQuery,
+ useInfraStatusQuery,
+ queryKeys,
+} from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
import { useToast } from '../components/Toast';
import './Plugins.css';
@@ -42,58 +50,33 @@ interface EngineConfig {
export default function Plugins() {
useDocumentTitle('Plugins');
const toast = useToast();
- const [plugins, setPlugins] = useState<Plugin[]>([]);
- const [engines, setEngines] = useState<Engine[]>([]);
- const [currentEngine, setCurrentEngine] = useState<string>('');
- const [loading, setLoading] = useState(true);
+ const queryClient = useQueryClient();
+ const { data: plugins = [], isLoading: loadingPlugins, error: queryError } = usePluginsQuery();
+ const { data: engines = [] } = useEnginesQuery();
+ const { data: currentEngineData } = useCurrentEngineQuery();
+ const { data: infraStatus } = useInfraStatusQuery();
+ const currentEngine = currentEngineData?.engineType ?? '';
+ const loading = loadingPlugins;
+ const error = queryError instanceof Error ? queryError.message : null;
const [actionLoading, setActionLoading] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
// Config modal state
const [showConfigModal, setShowConfigModal] = useState(false);
const [configPlugin, setConfigPlugin] = useState<Plugin | null>(null);
const [engineConfig, setEngineConfig] = useState<EngineConfig>({
- type: 'whatsapp-web.js',
- headless: true,
+ type: infraStatus?.engine?.type || 'whatsapp-web.js',
+ headless: infraStatus?.engine?.headless ?? true,
sessionDataPath: '/data/sessions',
browserArgs: '--no-sandbox --disable-gpu',
});
const [savingConfig, setSavingConfig] = useState(false);
- const fetchData = async () => {
- try {
- setLoading(true);
- setError(null);
- const [pluginsData, enginesData, currentEngineData, infraStatus] = await Promise.all([
- pluginsApi.list(),
- pluginsApi.getEngines(),
- pluginsApi.getCurrentEngine(),
- infraApi.getStatus(),
- ]);
- setPlugins(pluginsData);
- setEngines(enginesData);
- setCurrentEngine(currentEngineData.engineType);
-
- // Load engine config from infra status
- if (infraStatus.engine) {
- setEngineConfig({
- type: infraStatus.engine.type || 'whatsapp-web.js',
- headless: infraStatus.engine.headless ?? true,
- sessionDataPath: '/data/sessions',
- browserArgs: '--no-sandbox --disable-gpu',
- });
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to load plugins');
- } finally {
- setLoading(false);
- }
+ const refetchAll = () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.plugins });
+ void queryClient.invalidateQueries({ queryKey: queryKeys.engines });
+ void queryClient.invalidateQueries({ queryKey: queryKeys.currentEngine });
};
- useEffect(() => {
- fetchData();
- }, []);
-
const handleToggle = async (plugin: Plugin) => {
setActionLoading(plugin.id);
try {
@@ -102,9 +85,9 @@ export default function Plugins() {
} else {
await pluginsApi.enable(plugin.id);
}
- await fetchData();
+ refetchAll();
} catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to toggle plugin');
+ toast.error('Plugin Error', err instanceof Error ? err.message : 'Failed to toggle plugin');
} finally {
setActionLoading(null);
}
@@ -155,7 +138,7 @@ export default function Plugins() {
);
}
- const currentEngineData = engines.find(e => e.id === currentEngine);
+ const activeEngine = engines.find(e => e.id === currentEngine);
return (
<div className="plugins-page">
@@ -163,7 +146,7 @@ export default function Plugins() {
title="Plugins"
subtitle="Manage engines, storage backends, and extensions"
actions={
- <button className="btn-secondary" onClick={fetchData}>
+ <button className="btn-secondary" onClick={refetchAll}>
<RefreshCw size={16} />
Refresh
</button>
@@ -194,17 +177,17 @@ export default function Plugins() {
</div>
{/* Engine Features */}
- {currentEngineData && currentEngineData.features.length > 0 && (
+ {activeEngine && activeEngine.features.length > 0 && (
<div className="engine-features">
<p className="features-label">Supported Features:</p>
<div className="features-list">
- {currentEngineData.features.slice(0, 8).map(feature => (
+ {activeEngine.features.slice(0, 8).map(feature => (
<span key={feature} className="feature-tag">
{feature}
</span>
))}
- {currentEngineData.features.length > 8 && (
- <span className="feature-more">+{currentEngineData.features.length - 8} more</span>
+ {activeEngine.features.length > 8 && (
+ <span className="feature-more">+{activeEngine.features.length - 8} more</span>
)}
</div>
</div>
diff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsx
index 6570ad1a0..826270f95 100644
--- a/dashboard/src/pages/Webhooks.tsx
+++ b/dashboard/src/pages/Webhooks.tsx
@@ -11,9 +11,16 @@ import {
Check,
AlertTriangle,
} from 'lucide-react';
-import { webhookApi, sessionApi, type Webhook, type Session } from '../services/api';
+import { webhookApi, type Webhook } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useRole } from '../hooks/useRole';
+import {
+ useWebhooksQuery,
+ useSessionsQuery,
+ useCreateWebhookMutation,
+ useUpdateWebhookMutation,
+ useDeleteWebhookMutation,
+} from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
import './Webhooks.css';
@@ -29,9 +36,12 @@ const availableEvents = [
export function Webhooks() {
useDocumentTitle('Webhooks');
const { canWrite } = useRole();
- const [webhooks, setWebhooks] = useState<Webhook[]>([]);
- const [sessions, setSessions] = useState<Session[]>([]);
- const [loading, setLoading] = useState(true);
+ const { data: webhooks = [], isLoading: loadingWebhooks } = useWebhooksQuery();
+ const { data: sessions = [] } = useSessionsQuery();
+ const loading = loadingWebhooks;
+ const createMutation = useCreateWebhookMutation();
+ const updateMutation = useUpdateWebhookMutation();
+ const deleteMutation = useDeleteWebhookMutation();
const [showCreateModal, setShowCreateModal] = useState(false);
const [showEditModal, setShowEditModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
@@ -41,10 +51,6 @@ export function Webhooks() {
const [testingId, setTestingId] = useState<string | null>(null);
const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
- useEffect(() => {
- fetchData();
- }, []);
-
useEffect(() => {
if (toast) {
const timer = setTimeout(() => setToast(null), 4000);
@@ -52,30 +58,14 @@ export function Webhooks() {
}
}, [toast]);
- const fetchData = async () => {
- try {
- setLoading(true);
- const [webhooksData, sessionsData] = await Promise.all([
- webhookApi.listAll().catch(() => []),
- sessionApi.list().catch(() => []),
- ]);
- setWebhooks(webhooksData);
- setSessions(sessionsData);
- } catch (err) {
- console.error('Failed to fetch webhooks:', err);
- } finally {
- setLoading(false);
- }
- };
-
const handleCreate = async () => {
if (!newWebhook.url || !newWebhook.sessionId) return;
try {
- const created = await webhookApi.create(newWebhook.sessionId, {
+ await createMutation.mutateAsync({
+ sessionId: newWebhook.sessionId,
url: newWebhook.url,
events: newWebhook.events,
});
- setWebhooks([...webhooks, created]);
setShowCreateModal(false);
setNewWebhook({ url: '', events: ['message.received'], sessionId: '' });
setToast({ type: 'success', message: 'Webhook created successfully' });
@@ -95,8 +85,7 @@ export function Webhooks() {
const handleDelete = async () => {
if (!deleteTarget) return;
try {
- await webhookApi.delete(deleteTarget.sessionId, deleteTarget.id);
- setWebhooks(webhooks.filter(w => w.id !== deleteTarget.id));
+ await deleteMutation.mutateAsync({ sessionId: deleteTarget.sessionId, id: deleteTarget.id });
setShowDeleteModal(false);
setDeleteTarget(null);
setToast({ type: 'success', message: 'Webhook deleted successfully' });
@@ -135,12 +124,15 @@ export function Webhooks() {
const handleEdit = async () => {
if (!editWebhook) return;
try {
- const updated = await webhookApi.update(editWebhook.sessionId, editWebhook.id, {
- url: editWebhook.url,
- events: editWebhook.events,
- active: editWebhook.active,
+ await updateMutation.mutateAsync({
+ sessionId: editWebhook.sessionId,
+ id: editWebhook.id,
+ data: {
+ url: editWebhook.url,
+ events: editWebhook.events,
+ active: editWebhook.active,
+ },
});
- setWebhooks(webhooks.map(w => (w.id === updated.id ? updated : w)));
setShowEditModal(false);
setEditWebhook(null);
setToast({ type: 'success', message: 'Webhook updated successfully' });