@@ -30,6 +30,8 @@ import { Link } from '~/components/link';
3030import { usePathname , useRouter } from '~/i18n/routing' ;
3131import { useSearch } from '~/lib/search' ;
3232
33+ import { getLocalizedPathname } from './_actions/localized-pathname' ;
34+
3335interface Link {
3436 label : string ;
3537 href : string ;
@@ -862,22 +864,36 @@ function SearchResults({
862864 ) ;
863865}
864866
865- const useSwitchLocale = ( ) => {
867+ const useSwitchLocale = ( { activeLocale } : { activeLocale : Locale | undefined } ) => {
866868 const pathname = usePathname ( ) ;
867869 const router = useRouter ( ) ;
868870 const params = useParams ( ) ;
869871 const searchParams = useSearchParams ( ) ;
870872
871873 return useCallback (
872- ( locale : string ) =>
874+ async ( locale : string ) => {
875+ const localizedPathname = await getLocalizedPathname ( {
876+ pathname,
877+ activeLocale : activeLocale ?. id ,
878+ targetLocale : locale ,
879+ } ) ;
880+
881+ // the Next.js App Router guarantees a `startTransition` call on `router.push`,
882+ // so we don’t need to wrap it in an explicit nested call as set out in
883+ // https://react.dev/reference/react/useTransition#react-doesnt-treat-my-state-update-after-await-as-a-transition
873884 router . push (
874- // @ts -expect-error -- TypeScript will validate that only known `params`
875- // are used in combination with a given `pathname`. Since the two will
876- // always match for the current route, we can skip runtime checks.
877- { pathname, params, query : Object . fromEntries ( searchParams . entries ( ) ) } ,
885+ {
886+ pathname : localizedPathname ,
887+ // @ts -expect-error -- TypeScript will validate that only known `params`
888+ // are used in combination with a given `pathname`. Since the two will
889+ // always match for the current route, we can skip runtime checks.
890+ params,
891+ query : Object . fromEntries ( searchParams . entries ( ) ) ,
892+ } ,
878893 { locale } ,
879- ) ,
880- [ pathname , params , router , searchParams ] ,
894+ ) ;
895+ } ,
896+ [ pathname , activeLocale ?. id , params , router , searchParams ] ,
881897 ) ;
882898} ;
883899
@@ -892,7 +908,7 @@ function LocaleSwitcher({
892908} ) {
893909 const activeLocale = locales . find ( ( locale ) => locale . id === activeLocaleId ) ;
894910 const [ isPending , startTransition ] = useTransition ( ) ;
895- const switchLocale = useSwitchLocale ( ) ;
911+ const switchLocale = useSwitchLocale ( { activeLocale } ) ;
896912
897913 return (
898914 < div className = { className } >
0 commit comments