diff --git a/.changeset/heavy-berries-appear.md b/.changeset/heavy-berries-appear.md new file mode 100644 index 0000000000000..3ee6e91d4ac76 --- /dev/null +++ b/.changeset/heavy-berries-appear.md @@ -0,0 +1,9 @@ +--- +"@refinedev/core": patch +--- + +- Throw an error in `useGetLocale` if it is called without an i18n Provider. +- This ensures the hook's return type matches that of `i18nProvider.getLocale`. +- `useTranslation().getLocale` which is from `useGetLocale` now returns a string. + +[Resolves #6812](https://github.com/refinedev/refine/issues/6812) diff --git a/packages/core/src/hooks/i18n/useGetLocale.spec.tsx b/packages/core/src/hooks/i18n/useGetLocale.spec.tsx index 0de4ab27cd0d4..63f7ca6dfadba 100644 --- a/packages/core/src/hooks/i18n/useGetLocale.spec.tsx +++ b/packages/core/src/hooks/i18n/useGetLocale.spec.tsx @@ -4,10 +4,12 @@ import { useGetLocale } from "@hooks"; import { TestWrapper } from "@test"; describe("useGetLocale", () => { - it("should get undefined value if i18n provider not defined", () => { - const { result } = renderHook(() => useGetLocale()); + it("should throw error if i18n provider is not defined", () => { + const result = () => renderHook(() => useGetLocale()); - expect(result.current()).toBe(undefined); + expect(result).toThrow( + "useGetLocale cannot be called without i18n provider being defined.", + ); }); it("should get locale value from i18nProvider getLocale method", () => { diff --git a/packages/core/src/hooks/i18n/useGetLocale.ts b/packages/core/src/hooks/i18n/useGetLocale.ts index 7a9142ca27b32..f253c1db2263b 100644 --- a/packages/core/src/hooks/i18n/useGetLocale.ts +++ b/packages/core/src/hooks/i18n/useGetLocale.ts @@ -2,7 +2,7 @@ import { useCallback, useContext } from "react"; import { I18nContext } from "@contexts/i18n"; -export type UseGetLocaleType = () => () => string | undefined; +export type UseGetLocaleType = () => () => string; /** * If you need to know the current locale, refine provides the `useGetLocale` hook. @@ -13,5 +13,11 @@ export type UseGetLocaleType = () => () => string | undefined; export const useGetLocale: UseGetLocaleType = () => { const { i18nProvider } = useContext(I18nContext); - return useCallback(() => i18nProvider?.getLocale(), []); + if (!i18nProvider) { + throw new Error( + "useGetLocale cannot be called without i18n provider being defined.", + ); + } + + return useCallback(() => i18nProvider.getLocale(), []); };