+ {kind === "offline" ? (
+ "연결을 확인한 뒤 다시 시도해 주세요."
+ ) : (
+ <>
+ 서버가 응답하지 않아요. 잠시 후 다시 시도해 주세요.
+
+ 계속되면 개발팀에 알려 주세요 · 오류 코드 {kind}
+ >
+ )}
+
+
+
+
+
+
+ );
+}
diff --git a/src/features/dashboard/queries.ts b/src/features/dashboard/queries.ts
index e9c5ae8..5005f48 100644
--- a/src/features/dashboard/queries.ts
+++ b/src/features/dashboard/queries.ts
@@ -1,12 +1,12 @@
import { useQuery } from "@tanstack/react-query";
+import { loadQuery } from "@/lib/loadError";
import { getStats } from "./api";
export const useStats = () =>
useQuery({
queryKey: ["admin", "stats"],
queryFn: getStats,
- // 실패하면 기다리지 않고 바로 오류 화면을 띄운다. 다시 시도는 화면의 버튼으로 한다
- retry: false,
+ ...loadQuery,
// 화면 문구("10분마다 갱신")와 맞춘다
refetchInterval: 10 * 60 * 1000,
});
diff --git a/src/features/guides/components/GuidesError.tsx b/src/features/guides/components/GuidesError.tsx
new file mode 100644
index 0000000..71cadae
--- /dev/null
+++ b/src/features/guides/components/GuidesError.tsx
@@ -0,0 +1,48 @@
+import Button from "@/components/Button";
+
+// Figma W-4g
+// shortcut: 목록과 가이드를 한 번에 불러와서 실패하면 종 목록은 비워 둔다, 따로 불러오게 되면 시안처럼 목록을 보여 줌
+export default function GuidesError({ onRetry }: { onRetry: () => void }) {
+ return (
+
+
+
종 선택
+
+
+
가이드
+
+
+ !
+
+
가이드를 불러오지 못했어요
+
+ 잠시 후 다시 시도해 주세요. 저장된 가이드는 그대로예요.
+
+
+
+
+
+ 불러오지 못했어요
+
+
+
+
+
+
+
+ );
+}
diff --git a/src/features/guides/components/GuidesManager.tsx b/src/features/guides/components/GuidesManager.tsx
index 16a48a6..637c781 100644
--- a/src/features/guides/components/GuidesManager.tsx
+++ b/src/features/guides/components/GuidesManager.tsx
@@ -8,11 +8,14 @@ import { sections, type Content, type Guide, type Section } from "../data";
import { useGuides, useSaveGuide } from "../queries";
import AppCardPreview from "./AppCardPreview";
import GuideEditor from "./GuideEditor";
+import GuidesError from "./GuidesError";
import SpeciesList from "./SpeciesList";
export default function GuidesManager() {
- const { data } = useGuides();
- // shortcut: 불러오는 중·실패 화면은 시안이 없어 비워 둔다, 시안 나오면 추가
+ const { data, isError, refetch } = useGuides();
+ // 이미 받은 목록이 있으면 갱신이 실패해도 편집 화면(고치던 내용)을 그대로 둔다
+ if (isError && !data) return refetch()} />;
+ // shortcut: 불러오는 중 화면은 시안이 없어 비워 둔다, 시안 나오면 추가
return data?.length ? : null;
}
diff --git a/src/features/guides/queries.ts b/src/features/guides/queries.ts
index edfba78..601f9ca 100644
--- a/src/features/guides/queries.ts
+++ b/src/features/guides/queries.ts
@@ -1,4 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { loadQuery } from "@/lib/loadError";
import { fetchGuides, saveGuide } from "./api";
import type { Content, Guide } from "./data";
@@ -6,9 +7,8 @@ export const useGuides = () =>
useQuery({
queryKey: ["guides"],
queryFn: fetchGuides,
- // 대시보드(useStats)처럼 실패하면 기다리지 않고 바로 실패로 둔다.
- // 다시 시도하면 종 수만큼 요청이 또 나가는 것도 막는다
- retry: false,
+ // 자동 재시도가 없어 종 수만큼 요청이 또 나가는 것도 막는다
+ ...loadQuery,
// 창에 돌아오거나 화면에 다시 들어올 때마다 종 수만큼 다시 불러오지 않게 5분은 새것으로 본다
staleTime: 5 * 60 * 1000,
});
diff --git a/src/features/species/components/SpeciesManager.tsx b/src/features/species/components/SpeciesManager.tsx
index caa3b16..09ae602 100644
--- a/src/features/species/components/SpeciesManager.tsx
+++ b/src/features/species/components/SpeciesManager.tsx
@@ -15,7 +15,7 @@ import SpeciesTable, { type Species } from "./SpeciesTable";
type Editing = { target?: Species; draft: Partial; error?: string };
export default function SpeciesManager() {
- const { data: species } = useSpecies();
+ const { data, isError, refetch } = useSpecies();
const { mutateAsync: saveSpecies, isPending: saving } = useSaveSpecies();
const { mutateAsync: setHidden, isPending: hiddenPending } = useSetHidden();
const [query, setQuery] = useState("");
@@ -29,8 +29,10 @@ export default function SpeciesManager() {
return () => clearTimeout(id);
}, [toast]);
- // shortcut: 불러오는 중·실패 화면은 시안이 없어 비워 둔다 (가이드 화면과 같음), 시안 나오면 추가
- if (!species) return null;
+ // shortcut: 불러오는 중 화면은 시안이 없어 비워 둔다 (가이드 화면과 같음), 시안 나오면 추가
+ if (!data && !isError) return null;
+ const failed = !data;
+ const species = data ?? [];
const q = query.trim();
const rows = q ? species.filter((s) => s.name.includes(q)) : species;
@@ -96,9 +98,11 @@ export default function SpeciesManager() {
- {q
- ? `종 목록 · 검색 결과 ${rows.length}종`
- : `종 목록 · ${species.length}종`}
+ {failed
+ ? "종 목록"
+ : q
+ ? `종 목록 · 검색 결과 ${rows.length}종`
+ : `종 목록 · ${species.length}종`}
저장하면 앱의 종 선택 목록에 바로 반영돼요 · 숨긴 종은 회색으로
@@ -113,17 +117,31 @@ export default function SpeciesManager() {
onEdit={(s) => setEditing({ target: s, draft: s })}
onToggleHidden={toggleHidden}
empty={
-
-
- '{q}'와 맞는 종이 없어요
-
-
- 철자를 확인하거나 새 종으로 추가해 주세요.
-
-
-
+ failed ? (
+ // Figma W-3j
+
+
종 목록을 불러오지 못했어요
+
+ 잠시 후 다시 시도해 주세요. 계속되면 개발팀에 알려 주세요.
+
+
+
+ ) : (
+
+
+ '{q}'와 맞는 종이 없어요
+
+
+ 철자를 확인하거나 새 종으로 추가해 주세요.
+
+
+
+ )
}
/>
diff --git a/src/features/species/queries.ts b/src/features/species/queries.ts
index b85bad4..10692b4 100644
--- a/src/features/species/queries.ts
+++ b/src/features/species/queries.ts
@@ -1,4 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { loadQuery } from "@/lib/loadError";
import { getSpecies, saveSpecies, setHidden } from "./api";
import type { Species } from "./components/SpeciesTable";
@@ -8,8 +9,7 @@ export const useSpecies = () =>
useQuery({
queryKey: speciesKey,
queryFn: getSpecies,
- // 대시보드(useStats)처럼 실패하면 기다리지 않고 바로 실패로 둔다
- retry: false,
+ ...loadQuery,
});
// 서버가 저장한 종으로 목록 캐시를 바꾼다. 처음 보는 id면 새로 추가한 종이라 끝에 붙인다
diff --git a/src/lib/loadError.test.ts b/src/lib/loadError.test.ts
new file mode 100644
index 0000000..904f0b0
--- /dev/null
+++ b/src/lib/loadError.test.ts
@@ -0,0 +1,51 @@
+import { QueryClient, QueryObserver } from "@tanstack/react-query";
+import { afterEach, expect, test, vi } from "vitest";
+import { setServer } from "@/test/fakeServer";
+import { api } from "./api";
+import { commonError, loadQuery } from "./loadError";
+
+afterEach(() => vi.restoreAllMocks());
+
+const failure = (status: number) => {
+ setServer(() => [status, {}]);
+ return api.get("/admin/stats").catch((e: unknown) => e);
+};
+
+test("5xx는 상태 코드, 4xx와 그 밖의 에러는 화면별 실패 화면", async () => {
+ expect(commonError(await failure(500))).toBe(500);
+ expect(commonError(await failure(503))).toBe(503);
+ expect(commonError(await failure(404))).toBeUndefined();
+ expect(commonError(new Error("render"))).toBeUndefined();
+});
+
+test("응답이 없으면 브라우저가 오프라인일 때만 연결 끊김", async () => {
+ const { AxiosError } = await import("axios");
+ const noResponse = new AxiosError("Network Error");
+ expect(commonError(noResponse)).toBeUndefined();
+ vi.spyOn(navigator, "onLine", "get").mockReturnValue(false);
+ expect(commonError(noResponse)).toBe("offline");
+});
+
+test("받은 값이 있으면 갱신이 실패해도 공통 오류 화면으로 보내지 않는다", async () => {
+ const error = await failure(500);
+ expect(loadQuery.throwOnError(error, { state: { data: undefined } })).toBe(
+ true,
+ );
+ expect(loadQuery.throwOnError(error, { state: { data: {} } })).toBe(false);
+});
+
+test("오프라인이어도 요청을 미루지 않고 실패한다", async () => {
+ const { onlineManager } = await import("@tanstack/react-query");
+ onlineManager.setOnline(false);
+ const observer = new QueryObserver(new QueryClient(), {
+ ...loadQuery,
+ queryKey: ["x"],
+ queryFn: () => Promise.reject(new Error("offline")),
+ });
+ const unsubscribe = observer.subscribe(() => {});
+ await vi.waitFor(() =>
+ expect(observer.getCurrentResult().isError).toBe(true),
+ );
+ unsubscribe();
+ onlineManager.setOnline(true);
+});
diff --git a/src/lib/loadError.ts b/src/lib/loadError.ts
new file mode 100644
index 0000000..22d969f
--- /dev/null
+++ b/src/lib/loadError.ts
@@ -0,0 +1,21 @@
+import { isAxiosError } from "axios";
+
+// 공통 오류 화면(app/error.tsx)의 종류. "offline"은 W-E4, 숫자(5xx 상태 코드)는 W-E3.
+// undefined면 화면마다 있는 실패 화면(W-2a · W-3j · W-4g)이 맡는다
+export function commonError(error: unknown) {
+ if (!isAxiosError(error)) return;
+ const status = error.response?.status;
+ if (status === undefined) return navigator.onLine ? undefined : "offline";
+ return status >= 500 ? status : undefined;
+}
+
+// 화면을 처음 불러오는 쿼리의 공통 설정
+export const loadQuery = {
+ // 실패하면 기다리지 않고 바로 오류 화면을 띄운다. 다시 시도는 화면의 버튼으로 한다
+ retry: false,
+ // 기본값은 오프라인이면 요청을 미뤄 빈 화면에 멈추므로, 바로 보내서 실패하게 한다
+ networkMode: "always",
+ // 이미 받은 값이 있으면 자동 갱신이 실패해도 화면을 바꾸지 않는다
+ throwOnError: (error: unknown, query: { state: { data: unknown } }) =>
+ query.state.data === undefined && commonError(error) !== undefined,
+} as const;