Next.js Discord

Discord Forum

Client Side Language Switcher that needs to fetch data

Bengal posted this in #help-forum
Open in Discord
GitHub gist with files mentioned:

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 component

I 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.

- 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?

0 Replies