fix: preserve cached data during refresh failures

This commit is contained in:
2026-08-24 00:50:39 +03:00
parent 7a3048c347
commit 6d892da9ce
12 changed files with 511 additions and 61 deletions
+125
View File
@@ -0,0 +1,125 @@
import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { MemoryRouter } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import { brokerageAccountsQueryKey } from "@/entities/brokerage-account";
import { server } from "@/test/server";
import { AccountsPage } from "./AccountsPage";
vi.mock("@/features/auth", () => ({
useAuth: () => ({ accessToken: "test-token" }),
}));
const account = {
id: "account-1",
name: "Основной",
type: "BROKERAGE",
openedOn: "2026-01-01",
} as const;
function renderPage(queryClient: QueryClient) {
return render(
<QueryClientProvider client={queryClient}>
<MantineProvider>
<MemoryRouter>
<AccountsPage />
</MemoryRouter>
</MantineProvider>
</QueryClientProvider>,
);
}
describe("AccountsPage", () => {
afterEach(cleanup);
it("keeps the cached account list visible during a background refresh", async () => {
let requestCount = 0;
let resolveRefresh: ((response: Response) => void) | undefined;
server.use(
http.get("*/api/v1/brokerage-accounts", () => {
requestCount += 1;
if (requestCount === 1) return HttpResponse.json([account]);
return new Promise<Response>((resolve) => {
resolveRefresh = resolve;
});
}),
);
const queryClient = new QueryClient();
renderPage(queryClient);
await screen.findByText(account.name);
void queryClient.invalidateQueries({
queryKey: brokerageAccountsQueryKey,
});
await waitFor(() => expect(requestCount).toBe(2));
expect(screen.getByText(account.name)).toBeInTheDocument();
expect(
screen.getByRole("status", { name: "Обновляем данные" }),
).toBeInTheDocument();
resolveRefresh?.(HttpResponse.json([account]));
});
it("keeps the cached account list and offers retry after a refresh error", async () => {
let requestCount = 0;
server.use(
http.get("*/api/v1/brokerage-accounts", () => {
requestCount += 1;
if (requestCount === 1) return HttpResponse.json([account]);
if (requestCount === 2)
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
);
return HttpResponse.json([account]);
}),
);
const queryClient = new QueryClient();
renderPage(queryClient);
await screen.findByText(account.name);
void queryClient.invalidateQueries({
queryKey: brokerageAccountsQueryKey,
});
const warning = await screen.findByText(
"Не удалось обновить данные. Показаны последние полученные.",
);
expect(warning).toBeInTheDocument();
expect(screen.getByText(account.name)).toBeInTheDocument();
screen.getByRole("button", { name: "Повторить" }).click();
await waitFor(() => expect(requestCount).toBe(3));
});
it("keeps a cached empty account list visible after a refresh error", async () => {
let requestCount = 0;
server.use(
http.get("*/api/v1/brokerage-accounts", () => {
requestCount += 1;
if (requestCount === 1) return HttpResponse.json([]);
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
);
}),
);
const queryClient = new QueryClient();
renderPage(queryClient);
await screen.findByText("Нет инвестиционных счетов");
void queryClient.invalidateQueries({
queryKey: brokerageAccountsQueryKey,
});
expect(
await screen.findByText(
"Не удалось обновить данные. Показаны последние полученные.",
),
).toBeInTheDocument();
expect(screen.getByText("Нет инвестиционных счетов")).toBeInTheDocument();
});
});
+16 -2
View File
@@ -10,8 +10,22 @@ export function AccountsPage() {
const viewModel = useAccountsPageViewModel();
if (viewModel.state === "loading") return <AccountsPageLoading />;
if (viewModel.state === "error") return <AccountsPageError {...viewModel} />;
if (viewModel.state === "empty") return <AccountsPageEmpty />;
return <AccountsPageLoaded accounts={viewModel.accounts} />;
if (viewModel.state === "empty")
return (
<AccountsPageEmpty
refreshing={viewModel.refreshing}
refreshError={viewModel.refreshError}
retry={viewModel.retry}
/>
);
return (
<AccountsPageLoaded
accounts={viewModel.accounts}
refreshing={viewModel.refreshing}
refreshError={viewModel.refreshError}
retry={viewModel.retry}
/>
);
}
export {
+75 -6
View File
@@ -1,4 +1,12 @@
import { Button, Stack, Title } from "@mantine/core";
import {
Alert,
Button,
Group,
Loader,
Stack,
Text,
Title,
} from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import type { BrokerageAccount } from "@/entities/brokerage-account";
@@ -71,26 +79,87 @@ export function AccountsPageError({
);
}
export function AccountsPageEmpty() {
export function AccountsPageEmpty({
refreshing = false,
refreshError = false,
retry,
}: {
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
}) {
const { t } = useTranslation();
return (
<StateView
title={t("accounts.emptyTitle")}
text={t("accounts.emptyText")}
/>
<Stack>
<AccountsRefreshState
refreshing={refreshing}
refreshError={refreshError}
retry={retry}
/>
<StateView
title={t("accounts.emptyTitle")}
text={t("accounts.emptyText")}
/>
</Stack>
);
}
export function AccountsPageLoaded({
accounts,
refreshing = false,
refreshError = false,
retry,
}: {
accounts: BrokerageAccount[];
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
}) {
const { t } = useTranslation();
return (
<Stack>
<Title order={1}>{t("accounts.title")}</Title>
<AccountsRefreshState
refreshing={refreshing}
refreshError={refreshError}
retry={retry}
/>
<BrokerageAccountList accounts={accounts} />
</Stack>
);
}
function AccountsRefreshState({
refreshing,
refreshError,
retry,
}: {
refreshing: boolean;
refreshError: boolean;
retry?: () => void;
}) {
const { t } = useTranslation();
if (!refreshing && !refreshError) return null;
return (
<>
{refreshing ? (
<Group gap="xs" role="status" aria-label={t("accounts.refreshing")}>
<Loader size="sm" />
<Text c="dimmed" size="sm">
{t("accounts.refreshing")}
</Text>
</Group>
) : null}
{refreshError ? (
<Alert color="orange">
<Stack gap="sm">
<Text>{t("accounts.refreshError")}</Text>
<Button onClick={retry} variant="light">
{t("accounts.retry")}
</Button>
</Stack>
</Alert>
) : null}
</>
);
}
+20 -6
View File
@@ -4,13 +4,27 @@ import { useAuth } from "@/features/auth";
export function useAccountsPageViewModel() {
const { accessToken } = useAuth();
const accounts = useBrokerageAccounts(accessToken);
if (accounts.isFetching) return { state: "loading" as const };
if (accounts.isError)
if (!accounts.data) {
if (accounts.isFetching) return { state: "loading" as const };
if (accounts.isError)
return {
state: "error" as const,
code: errorCode(accounts.error),
retry: () => accounts.refetch(),
};
}
if (!accounts.data?.length)
return {
state: "error" as const,
code: errorCode(accounts.error),
state: "empty" as const,
refreshing: accounts.isFetching,
refreshError: accounts.isError,
retry: () => accounts.refetch(),
};
if (!accounts.data?.length) return { state: "empty" as const };
return { state: "loaded" as const, accounts: accounts.data };
return {
state: "loaded" as const,
accounts: accounts.data,
refreshing: accounts.isFetching,
refreshError: accounts.isError,
retry: () => accounts.refetch(),
};
}