Next.js Discord

Discord Forum

Lang Switcher

Answered
Southern rough shrimp posted this in #help-forum
Open in Discord
Southern rough shrimpOP
Hello, everyone. I have a case like this:
There is a news page /app/news/[slug]/page.tsx, 1 news item has 3 languages. That is, the "Headline of some news" has 3 slugs for 3 different languages. How can I get/transfer all these 3 slugs from /app/news/[slug]/page.tsx to <Header /> for output to <Link> (language switcher) without losing SSR?

<Header /> is located in the RootLayout
Answered by Asian paper wasp
Right, so what you should be doing is not "transfer all these 3 slugs" to <Header />. Instead, you should call the same API in <Header />.

And in case you are wondering, yes, that's a duplicated API call, but here's where the fetch() and React.cache() deduplication comes in. At the end of the day, the fetcher (aka function) is called twice, but only the 1st call will actually fire the API, while the 2nd call will reuse the cached response
View full answer

8 Replies

Asian paper wasp
How is the info of "3 slugs for 3 different languages" being obtained? From some sort of API?
Southern rough shrimpOP
Yes, this information is added to all data in the news.
Asian paper wasp
Right, so what you should be doing is not "transfer all these 3 slugs" to <Header />. Instead, you should call the same API in <Header />.

And in case you are wondering, yes, that's a duplicated API call, but here's where the fetch() and React.cache() deduplication comes in. At the end of the day, the fetcher (aka function) is called twice, but only the 1st call will actually fire the API, while the 2nd call will reuse the cached response
Answer
Asian paper wasp
As a side note, the same news article with multi-language is usually done via /news/:langCode:/:slug, where all 3 articles share the same slug.
Southern rough shrimpOP
Hmm.... Is it better to use parallel routes to get a slug from a url? I really need <Header/> to remain a server component.
Is there an easier way?
Asian paper wasp
You can fetch APIs from a server component.
In fact, deduplication only works in server components