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?