Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useLocale returns locale from path params instead of provider value in client components #688

Closed
cbodin opened this issue Dec 4, 2023 · 2 comments · Fixed by #691
Closed
Labels
bug Something isn't working unconfirmed Needs triage.

Comments

@cbodin
Copy link

cbodin commented Dec 4, 2023

Description

useLocale will always return the locale path parameter in client components even though NextIntlClientProvider is configured with a hard-coded locale.

I cannot find anything related to this behaviour in the documentation so this should probably be documented and/or add an option to useLocale to retrieve the locale from the provider and not the path parameters for client components.

// The types aren't entirely correct here. Outside of Next.js
// `useParams` can be called, but the return type is `null`.
const params = useParams() as ReturnType<typeof useParams> | null;
if (typeof params?.[LOCALE_SEGMENT_NAME] === 'string') {
locale = params[LOCALE_SEGMENT_NAME];
} else {
// eslint-disable-next-line react-hooks/rules-of-hooks -- Reading from context conditionally is fine as long as we're in the render phase
locale = useBaseLocale();
}

Mandatory reproduction URL (CodeSandbox or GitHub repository)

https://codesandbox.io/p/devbox/next-intl-bug-template-app-forked-w4q7qq

Reproduction description

  1. Open up the /_next/info page and view the resulting locales.
  2. Open up the /en/info page and view the resulting locales.
  3. Remove the notFound(); call in src/app/[locale]/layout.tsx.
  4. Open up the /_next/info page and view the resulting locales.

Expected behaviour

The universal "useLocale" hook should return the expected locale configured in the provider in client components.
All displayed locales should be "en" in client components.

This ensures that components can be re-used in 404:s from _next/* paths.

@amannn
Copy link
Owner

amannn commented Dec 5, 2023

Thank you so much for the great bug report!

I agree, this is indeed a bit confusing. #691 will fix this.

amannn added a commit that referenced this issue Dec 5, 2023
…ale` in Client Components. `useParams().locale` is still used as a fallback. (#691)

Fixes #688
@cbodin
Copy link
Author

cbodin commented Dec 5, 2023

Thanks @amannn, works perfectly now!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working unconfirmed Needs triage.
Projects
None yet
2 participants