Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
104
rated 0 times [  105] [ 1]  / answers: 1 / hits: 7275  / 3 Years ago, sat, november 20, 2021, 12:00:00

I have a central place to change locale. I show a list of locales, and when the user clicks on any of them, I use useRouter to redirect the user to the current page, but in the selected locale:


var router = useRouter();

const changeLocale = (selectedLocal) => {
router.push({
pathname: router.pathname,
query: router.query
}, {
pathname: router.pathname,
query: router.query
}, { locale });
}

<div onClick={() => changeLocale('fr')}>Fr</div>

It works very well for URLs that have no parameters. But when the URL has parameters, it gets duplicated. For example, I have a list of conferences and when the user clicks on a conference I'll take him to the conference page using this Link:


<Link
href={{
pathname: '/conference/[id]',
query: { id: conf.id }
}}

This takes the user to the example.com/conference/5 for example. But when the user changes the locale on that page, I see the URL is changed to example.com/conference/5?id=5. As you can see, I have two duplicated id parameters here. And If I don't pass query to router.push, I see this error:



Error: The provided href (/conference/[id]) value is missing query values (id) to be interpolated properly. Read more: https://nextjs.org/docs/messages/href-interpolation-failed



How should I effectively reroute users and keep URL structure and parameters?


More From » routes

 Answers
7

This worked for me:


    const changeLocale = (locale) => {
router.push({
route: router.pathname,
query: router.query
}, router.asPath, { locale });
}

Basically, I only changed the second parameter of the router.push method.


I took it from the docs:



Note that to handle switching only the locale while preserving all routing information such as dynamic route query values or hidden href query values, you can provide the href parameter as an object:



import { useRouter } from 'next/router'
const router = useRouter()
const { pathname, asPath, query } = router
// change just the locale and maintain all other route information including href's query
router.push({ pathname, query }, asPath, { locale: nextLocale })

[#668] Tuesday, November 9, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminuniquer

Total Points: 63
Total Questions: 121
Total Answers: 96

Location: Cambodia
Member since Thu, May 21, 2020
4 Years ago
;