Jiseoup/showmycodePublic
EN|KO
  • Code
  • Commits
  • Pull Requests
← Back to list
Merged

fix: preserve query params when switching locale

#22
JiseoupJiseoup · Jun 16, 2026fix/locale-switch-preserve-query → main
fix
OverviewCommitsFiles changed
Changed files

+22 -3 · 1

@@ -1,19 +1,22 @@
"use client";
+import { Suspense } from "react";
import Link from "next/link";
-import { usePathname } from "next/navigation";
+import { usePathname, useSearchParams } from "next/navigation";
import { locales, type Locale } from "@/lib/i18n";
const labels: Record<Locale, string> = { ko: "KO", en: "EN" };
-export function LangSwitcher({ currentLang }: { currentLang: Locale }) {
+function LangLinks({ currentLang, query }: { currentLang: Locale; query: string }) {
const pathname = usePathname();
function switchTo(lang: Locale) {
// Replace the locale segment: /ko/... → /en/... or /ko → /en.
const segments = pathname.split("/");
segments[1] = lang;
- return segments.join("/") || "/";
+ const path = segments.join("/") || "/";
+ // Keep query params so locale switches preserve tab, page, and file/branch.
+ return query ? `${path}?${query}` : path;
}
return (
@@ -36,3 +39,19 @@ export function LangSwitcher({ currentLang }: { currentLang: Locale }) {
</div>
);
}
+
+// Reads the query string; isolated so the Suspense boundary can prerender the rest.
+function QueryAwareLangLinks({ currentLang }: { currentLang: Locale }) {
+ const query = useSearchParams().toString();
+ return <LangLinks currentLang={currentLang} query={query} />;
+}
+
+export function LangSwitcher({ currentLang }: { currentLang: Locale }) {
+ // useSearchParams requires a Suspense boundary to keep prerendered routes static.
+ // The fallback renders the switcher without query params (the value during prerender).
+ return (
+ <Suspense fallback={<LangLinks currentLang={currentLang} query="" />}>
+ <QueryAwareLangLinks currentLang={currentLang} />
+ </Suspense>
+ );
+}