NextJS - Appending a query param to a dynamic route

我只是一个虾纸丫 提交于 2020-12-13 07:59:51

问题


In my NextJS app, I have a language selector that's visible on every page. When I select a new language, I just want to replace the current URL by appending a query param lang=en to it.

Here's the function that replaces the URL:

const changeLanguage = (lang: LanguageID) => {
    replace({
      pathname,
      query: { ...query, lang },
    });
  };

In this example, replace, query and pathname are coming from the next router.

Now, everything works for static routes, but I'm unable to make it work for dynamic routes. For example, I have the following folder structure:

pages
|_customers
|__index.tsx
|__[customerId].tsx

If I'm on http://localhost/customers and I change my language to English, the URL changes to http://localhost/customers?lang=en which is what I want. However, if I'm on http://localhost/customer/1 and I change my language to English, the URL changes to http://localhost/customers/[customerId]?customerId=1&lang=en, instead of the URL I'm expecting http://localhost/customers/1?lang=en.

Now, I know that I could use asPath on the router, and reconstruct the query string object by appending lang to it, but I feel that it's something that should be build into Next. Also, I know it could be easily done with vanilla JS, but it's not the point here.

Am I missing something? Is there an easier way to append query params to a dynamic route without doing a server-side re-rendering?

Thanks


回答1:


I ended up using the solution that I wanted to avoid in the first place, which was to play with the asPath value. Atleast, there's no server-side re-rendering being done since the path is the same.

Here's my updated changeLanguage function (stringifyUrl is coming from the query-string package)

  const changeLanguage = (lang: LanguageID) => {
    const newPathname = stringifyUrl({ url: pathname, query: { ...query, lang } });
    const newAsPath = stringifyUrl({ url: asPath, query: { lang } });
    replace(newPathname, newAsPath);
  };


来源:https://stackoverflow.com/questions/61466891/nextjs-appending-a-query-param-to-a-dynamic-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!