feat: integrate React Query for data fetching and state management across dashboard components
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { use, useCallback, useEffect, useState } from "react";
|
||||
import { use, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
Button,
|
||||
@@ -93,14 +94,8 @@ type EditForm = {
|
||||
export default function ChargePointDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = use(params);
|
||||
|
||||
const [cp, setCp] = useState<ChargePointDetail | null>(null);
|
||||
const [notFound, setNotFound] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// transactions
|
||||
const [txData, setTxData] = useState<PaginatedTransactions | null>(null);
|
||||
const [txPage, setTxPage] = useState(1);
|
||||
const [txLoading, setTxLoading] = useState(true);
|
||||
|
||||
// edit modal
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
@@ -112,42 +107,22 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
feePerKwh: "0",
|
||||
});
|
||||
|
||||
const loadCp = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await api.chargePoints.get(id);
|
||||
setCp(data);
|
||||
} catch {
|
||||
setNotFound(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
const loadTx = useCallback(
|
||||
async (p: number) => {
|
||||
setTxLoading(true);
|
||||
try {
|
||||
const data = await api.transactions.list({
|
||||
page: p,
|
||||
limit: TX_LIMIT,
|
||||
chargePointId: id,
|
||||
const cpQuery = useQuery({
|
||||
queryKey: ["chargePoint", id],
|
||||
queryFn: () => api.chargePoints.get(id),
|
||||
refetchInterval: 3_000,
|
||||
retry: false,
|
||||
});
|
||||
setTxData(data);
|
||||
} finally {
|
||||
setTxLoading(false);
|
||||
}
|
||||
},
|
||||
[id],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
loadCp();
|
||||
}, [loadCp]);
|
||||
const txQuery = useQuery({
|
||||
queryKey: ["chargePointTransactions", id, txPage],
|
||||
queryFn: () =>
|
||||
api.transactions.list({ page: txPage, limit: TX_LIMIT, chargePointId: id }),
|
||||
refetchInterval: 3_000,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
loadTx(txPage);
|
||||
}, [txPage, loadTx]);
|
||||
const cp = cpQuery.data;
|
||||
const txData = txQuery.data;
|
||||
|
||||
const openEdit = () => {
|
||||
if (!cp) return;
|
||||
@@ -165,13 +140,13 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
setEditBusy(true);
|
||||
try {
|
||||
const fee = Math.max(0, Math.round(Number(editForm.feePerKwh) || 0));
|
||||
const updated = await api.chargePoints.update(cp.id, {
|
||||
await api.chargePoints.update(cp.id, {
|
||||
chargePointVendor: editForm.chargePointVendor,
|
||||
chargePointModel: editForm.chargePointModel,
|
||||
registrationStatus: editForm.registrationStatus,
|
||||
feePerKwh: fee,
|
||||
});
|
||||
setCp((prev) => (prev ? { ...prev, ...updated, connectors: prev.connectors } : prev));
|
||||
await cpQuery.refetch();
|
||||
setEditOpen(false);
|
||||
} finally {
|
||||
setEditBusy(false);
|
||||
@@ -188,7 +163,7 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
|
||||
// ── Render: loading / not found ──────────────────────────────────────────
|
||||
|
||||
if (loading) {
|
||||
if (cpQuery.isPending) {
|
||||
return (
|
||||
<div className="flex h-48 items-center justify-center">
|
||||
<Spinner />
|
||||
@@ -196,7 +171,7 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
);
|
||||
}
|
||||
|
||||
if (notFound || !cp) {
|
||||
if (!cp) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Link
|
||||
@@ -463,7 +438,7 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
<Table.Body
|
||||
renderEmptyState={() => (
|
||||
<div className="py-8 text-center text-sm text-muted">
|
||||
{txLoading ? "加载中…" : "暂无充电记录"}
|
||||
{txQuery.isPending ? "加载中…" : "暂无充电记录"}
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Button,
|
||||
Chip,
|
||||
@@ -67,26 +68,17 @@ const EMPTY_FORM: FormData = {
|
||||
};
|
||||
|
||||
export default function ChargePointsPage() {
|
||||
const [chargePoints, setChargePoints] = useState<ChargePoint[]>([]);
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [formTarget, setFormTarget] = useState<ChargePoint | null>(null);
|
||||
const [formData, setFormData] = useState<FormData>(EMPTY_FORM);
|
||||
const [formBusy, setFormBusy] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<ChargePoint | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const hasFetched = useRef(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const data = await api.chargePoints.list().catch(() => []);
|
||||
setChargePoints(data);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasFetched.current) {
|
||||
hasFetched.current = true;
|
||||
load();
|
||||
}
|
||||
}, [load]);
|
||||
const { data: chargePoints = [], refetch: refetchList } = useQuery({
|
||||
queryKey: ["chargePoints"],
|
||||
queryFn: () => api.chargePoints.list().catch(() => []),
|
||||
refetchInterval: 3_000,
|
||||
});
|
||||
|
||||
const openCreate = () => {
|
||||
setFormTarget(null);
|
||||
@@ -113,28 +105,23 @@ export default function ChargePointsPage() {
|
||||
const fee = Math.max(0, Math.round(Number(formData.feePerKwh) || 0));
|
||||
if (formTarget) {
|
||||
// Edit
|
||||
const updated = await api.chargePoints.update(String(formTarget.id), {
|
||||
await api.chargePoints.update(String(formTarget.id), {
|
||||
chargePointVendor: formData.chargePointVendor,
|
||||
chargePointModel: formData.chargePointModel,
|
||||
registrationStatus: formData.registrationStatus,
|
||||
feePerKwh: fee,
|
||||
});
|
||||
setChargePoints((prev) =>
|
||||
prev.map((cp) =>
|
||||
cp.id === formTarget.id ? { ...updated, connectors: cp.connectors } : cp,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Create
|
||||
const created = await api.chargePoints.create({
|
||||
await api.chargePoints.create({
|
||||
chargePointIdentifier: formData.chargePointIdentifier.trim(),
|
||||
chargePointVendor: formData.chargePointVendor.trim() || undefined,
|
||||
chargePointModel: formData.chargePointModel.trim() || undefined,
|
||||
registrationStatus: formData.registrationStatus,
|
||||
feePerKwh: fee,
|
||||
});
|
||||
setChargePoints((prev) => [created, ...prev]);
|
||||
}
|
||||
await refetchList();
|
||||
setFormOpen(false);
|
||||
} finally {
|
||||
setFormBusy(false);
|
||||
@@ -146,7 +133,7 @@ export default function ChargePointsPage() {
|
||||
setDeleting(true);
|
||||
try {
|
||||
await api.chargePoints.delete(String(deleteTarget.id));
|
||||
setChargePoints((prev) => prev.filter((cp) => cp.id !== deleteTarget.id));
|
||||
await refetchList();
|
||||
setDeleteTarget(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Autocomplete,
|
||||
Button,
|
||||
@@ -22,7 +23,7 @@ import {
|
||||
useFilter,
|
||||
} from "@heroui/react";
|
||||
import { parseDate } from "@internationalized/date";
|
||||
import { Pencil, Plus, TrashBin } from "@gravity-ui/icons";
|
||||
import { ArrowRotateRight, Pencil, Plus, TrashBin } from "@gravity-ui/icons";
|
||||
import { api, type IdTag, type UserRow } from "@/lib/api";
|
||||
import { useSession } from "@/lib/auth-client";
|
||||
|
||||
@@ -330,43 +331,36 @@ function TagFormBody({
|
||||
export default function IdTagsPage() {
|
||||
const { data: sessionData } = useSession();
|
||||
const isAdmin = sessionData?.user?.role === "admin";
|
||||
const [tags, setTags] = useState<IdTag[]>([]);
|
||||
const [users, setUsers] = useState<UserRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [editing, setEditing] = useState<IdTag | null>(null);
|
||||
const [form, setForm] = useState<FormState>(emptyForm);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [deletingTag, setDeletingTag] = useState<string | null>(null);
|
||||
const [claiming, setClaiming] = useState(false);
|
||||
|
||||
const handleClaim = async () => {
|
||||
setClaiming(true);
|
||||
try {
|
||||
await api.idTags.claim();
|
||||
await load();
|
||||
} finally {
|
||||
setClaiming(false);
|
||||
}
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const { data: idTagsData, isPending: loading, isFetching: refreshing, refetch } = useQuery({
|
||||
queryKey: ["idTags"],
|
||||
queryFn: async () => {
|
||||
const [tagList, userList] = await Promise.all([
|
||||
api.idTags.list(),
|
||||
api.users.list().catch(() => [] as UserRow[]),
|
||||
]);
|
||||
setTags(tagList);
|
||||
setUsers(userList);
|
||||
return { tags: tagList, users: userList };
|
||||
},
|
||||
});
|
||||
|
||||
const tags = idTagsData?.tags ?? [];
|
||||
const users = idTagsData?.users ?? [];
|
||||
|
||||
const handleClaim = async () => {
|
||||
setClaiming(true);
|
||||
try {
|
||||
await api.idTags.claim();
|
||||
await refetch();
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setClaiming(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setForm(emptyForm);
|
||||
@@ -405,7 +399,7 @@ export default function IdTagsPage() {
|
||||
balance: yuanToFen(form.balance),
|
||||
});
|
||||
}
|
||||
await load();
|
||||
await refetch();
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -415,7 +409,7 @@ export default function IdTagsPage() {
|
||||
setDeletingTag(idTag);
|
||||
try {
|
||||
await api.idTags.delete(idTag);
|
||||
await load();
|
||||
await refetch();
|
||||
} finally {
|
||||
setDeletingTag(null);
|
||||
}
|
||||
@@ -429,6 +423,17 @@ export default function IdTagsPage() {
|
||||
<p className="mt-0.5 text-sm text-muted">共 {tags.length} 张</p>
|
||||
</div>
|
||||
{isAdmin ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
isDisabled={refreshing}
|
||||
onPress={() => refetch()}
|
||||
aria-label="刷新"
|
||||
>
|
||||
<ArrowRotateRight className={`size-4 ${refreshing ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
<Modal>
|
||||
<Button size="sm" variant="secondary" onPress={openCreate}>
|
||||
<Plus className="size-4" />
|
||||
@@ -462,6 +467,7 @@ export default function IdTagsPage() {
|
||||
</Modal.Container>
|
||||
</Modal.Backdrop>
|
||||
</Modal>
|
||||
</div>
|
||||
) : (
|
||||
<Button size="sm" variant="secondary" isDisabled={claiming} onPress={handleClaim}>
|
||||
<Plus className="size-4" />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ReactNode } from 'react'
|
||||
import Sidebar from '@/components/sidebar'
|
||||
import { ReactQueryProvider } from '@/components/query-provider'
|
||||
|
||||
export default function DashboardLayout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
@@ -10,7 +11,9 @@ export default function DashboardLayout({ children }: { children: ReactNode }) {
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<main className="flex-1 overflow-y-auto pt-14 lg:pt-0">
|
||||
<div className="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
|
||||
<ReactQueryProvider>
|
||||
{children}
|
||||
</ReactQueryProvider>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Card, Spinner } from "@heroui/react";
|
||||
import {
|
||||
Thunderbolt,
|
||||
@@ -191,37 +191,21 @@ export default function DashboardPage() {
|
||||
const { data: sessionData, isPending } = useSession();
|
||||
const isAdmin = sessionData?.user?.role === "admin";
|
||||
|
||||
const [adminStats, setAdminStats] = useState<Stats | null>(null);
|
||||
const [userStats, setUserStats] = useState<UserStats | null>(null);
|
||||
const [recentTxns, setRecentTxns] = useState<Transaction[]>([]);
|
||||
const [chargePoints, setChargePoints] = useState<ChargePoint[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (isPending) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const [statsData, txnsData, cpsData] = await Promise.all([
|
||||
const { data, isPending: queryPending } = useQuery({
|
||||
queryKey: ["dashboard", isAdmin],
|
||||
queryFn: async () => {
|
||||
const [statsRes, txRes, cpsData] = await Promise.all([
|
||||
api.stats.get(),
|
||||
api.transactions.list({ limit: 6 }),
|
||||
isAdmin ? api.chargePoints.list() : Promise.resolve(null),
|
||||
isAdmin ? api.chargePoints.list() : Promise.resolve([] as ChargePoint[]),
|
||||
]);
|
||||
if ("totalChargePoints" in statsData) {
|
||||
setAdminStats(statsData as Stats);
|
||||
} else {
|
||||
setUserStats(statsData as UserStats);
|
||||
}
|
||||
setRecentTxns(txnsData.data);
|
||||
if (cpsData) setChargePoints(cpsData);
|
||||
} catch {}
|
||||
finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [isPending, isAdmin]);
|
||||
return { stats: statsRes, txns: txRes.data, cps: cpsData };
|
||||
},
|
||||
refetchInterval: 3_000,
|
||||
enabled: !isPending,
|
||||
});
|
||||
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
|
||||
if (isPending || loading) {
|
||||
if (isPending || queryPending) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
@@ -238,7 +222,7 @@ export default function DashboardPage() {
|
||||
// ── Admin view ────────────────────────────────────────────────────────────
|
||||
|
||||
if (isAdmin) {
|
||||
const s = adminStats;
|
||||
const s = data?.stats as Stats | undefined;
|
||||
const todayKwh = s ? (s.todayEnergyWh / 1000).toFixed(1) : "—";
|
||||
const todayRevenue = s ? `¥${(s.todayRevenue / 100).toFixed(2)}` : "—";
|
||||
const offlineCount = (s?.totalChargePoints ?? 0) - (s?.onlineChargePoints ?? 0);
|
||||
@@ -327,12 +311,12 @@ export default function DashboardPage() {
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-5">
|
||||
<div className="lg:col-span-2">
|
||||
<Panel title="充电桩状态">
|
||||
<ChargePointStatus cps={chargePoints} />
|
||||
<ChargePointStatus cps={data?.cps ?? []} />
|
||||
</Panel>
|
||||
</div>
|
||||
<div className="lg:col-span-3">
|
||||
<Panel title="最近充电会话">
|
||||
<RecentTransactions txns={recentTxns} />
|
||||
<RecentTransactions txns={data?.txns ?? []} />
|
||||
</Panel>
|
||||
</div>
|
||||
</div>
|
||||
@@ -342,7 +326,7 @@ export default function DashboardPage() {
|
||||
|
||||
// ── User view ─────────────────────────────────────────────────────────────
|
||||
|
||||
const s = userStats;
|
||||
const s = data?.stats as UserStats | undefined;
|
||||
const totalYuan = s ? (s.totalBalance / 100).toFixed(2) : "—";
|
||||
const todayKwh = s ? (s.todayEnergyWh / 1000).toFixed(2) : "—";
|
||||
|
||||
@@ -394,7 +378,7 @@ export default function DashboardPage() {
|
||||
</div>
|
||||
|
||||
<Panel title="最近充电记录">
|
||||
<RecentTransactions txns={recentTxns} />
|
||||
<RecentTransactions txns={data?.txns ?? []} />
|
||||
</Panel>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Button, Chip, Modal, Pagination, Spinner, Table } from "@heroui/react";
|
||||
import { TrashBin } from "@gravity-ui/icons";
|
||||
import { api, type PaginatedTransactions } from "@/lib/api";
|
||||
@@ -21,30 +22,21 @@ function formatDuration(start: string, stop: string | null): string {
|
||||
export default function TransactionsPage() {
|
||||
const { data: sessionData } = useSession();
|
||||
const isAdmin = sessionData?.user?.role === "admin";
|
||||
const [data, setData] = useState<PaginatedTransactions | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [status, setStatus] = useState<"all" | "active" | "completed">("all");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [stoppingId, setStoppingId] = useState<number | null>(null);
|
||||
const [deletingId, setDeletingId] = useState<number | null>(null);
|
||||
|
||||
const load = useCallback(async (p: number, s: typeof status) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.transactions.list({
|
||||
page: p,
|
||||
const { data, isPending: loading, refetch } = useQuery({
|
||||
queryKey: ["transactions", page, status],
|
||||
queryFn: () =>
|
||||
api.transactions.list({
|
||||
page,
|
||||
limit: LIMIT,
|
||||
status: s === "all" ? undefined : s,
|
||||
status: status === "all" ? undefined : status,
|
||||
}),
|
||||
refetchInterval: 3_000,
|
||||
});
|
||||
setData(res);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load(page, status);
|
||||
}, [page, status, load]);
|
||||
|
||||
const handleStatusChange = (s: typeof status) => {
|
||||
setStatus(s);
|
||||
@@ -55,7 +47,7 @@ export default function TransactionsPage() {
|
||||
setStoppingId(id);
|
||||
try {
|
||||
await api.transactions.stop(id);
|
||||
await load(page, status);
|
||||
await refetch();
|
||||
} finally {
|
||||
setStoppingId(null);
|
||||
}
|
||||
@@ -65,7 +57,7 @@ export default function TransactionsPage() {
|
||||
setDeletingId(id);
|
||||
try {
|
||||
await api.transactions.delete(id);
|
||||
await load(page, status);
|
||||
await refetch();
|
||||
} finally {
|
||||
setDeletingId(null);
|
||||
}
|
||||
|
||||
18
apps/web/components/query-provider.tsx
Normal file
18
apps/web/components/query-provider.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
|
||||
export function ReactQueryProvider({ children }: { children: React.ReactNode }) {
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 10_000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
"@heroui/react": "3.0.0-beta.8",
|
||||
"@heroui/styles": "3.0.0-beta.8",
|
||||
"@internationalized/date": "^3.12.0",
|
||||
"@tanstack/react-query": "^5.90.21",
|
||||
"better-auth": "^1.3.34",
|
||||
"next": "16.1.6",
|
||||
"react": "19.2.3",
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
"oxlint": "^1.52.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "^1.5.4"
|
||||
"@better-auth/passkey": "^1.5.4",
|
||||
"@tanstack/react-query": "^5.90.21"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user