Client Side Language Switcher that needs to fetch data
Unanswered
Bengal posted this in #help-forum
![Avatar](https://cdn.discordapp.com/embed/avatars/0.png)
BengalOP
GitHub gist with files mentioned:
https://gist.github.com/AnasGamal/0dfde3e4879ac405f3cf8c8f3cb10125
Issue:
I am using Next.js 13 and the app router. My application follows a specific structure: the
Here's an overview of the components and their types:
-
-
-
I am using the Strapi CMS and handling a case where the URL slugs should be unique for different languages. In the
Strapi's API provides a
The issue arises when fetching in the
Constraints:
-
-
How can I ensure that the
https://gist.github.com/AnasGamal/0dfde3e4879ac405f3cf8c8f3cb10125
Issue:
I am using Next.js 13 and the app router. My application follows a specific structure: the
layout.tsx
file sets the RootLayout
, which includes a Navbar.tsx
component. The Navbar.tsx
component renders the localeSwitcher.tsx
component.Here's an overview of the components and their types:
-
layout.tsx
is a server component-
Navbar.tsx
is a client component-
localeSwitcher.tsx
is a client componentI am using the Strapi CMS and handling a case where the URL slugs should be unique for different languages. In the
localeSwitcher.tsx
component, I retrieve the current client URL using usePathname
, which can only be used in a client component. This URL helps me determine the current language and section of the website the client is on (e.g., /en/blog/category/article
).Strapi's API provides a
localizations
array for a fetched article, which contains information such as the ID and unique slug for the localized versions of the requested article. For example, if I request an English article, the localizations
array will provide information about the French version, allowing me to redirect to the French version with its unique slug.The issue arises when fetching in the
localeSwitcher.tsx
component. The fetch takes some time, and the rest of the page loads before the localeSwitcher
fetches the localized slug. This results in the localeSwitcher
not always having an up-to-date localized slug.Constraints:
-
localeSwitcher
must be a client component because only client components have access to usePathname
, which is the reliable way to get the current URL.-
localeSwitcher
cannot be an async function, as it causes issues due to client components not supporting async functions.How can I ensure that the
localeSwitcher
always has an up-to-date localized slug?