UNPKG

@intl-t/react

Version:

A Fully-Typed Object-Based i18n Translation Library for React

43 lines (42 loc) 1.53 kB
"use client"; import { hydration as h } from "@intl-t/global"; import { getClientLocale, setClientLocale, LOCALE_CLIENT_KEY } from "@intl-t/react/client"; import { TranslationContext } from "@intl-t/react/context"; import { useState, useEffect, useContext, useMemo } from "react"; export function useLocale( // @ts-ignore-error optional binding defaultLocale = this?.locale, { hydration = h, path, } = this?.settings || {}) { path &&= `${LOCALE_CLIENT_KEY}${path}`; // @ts-ignore-error optional binding const t = this; const context = !defaultLocale && useContext(TranslationContext)?.localeState; if (context) return context; const state = useState((!hydration && getClientLocale.call(t, path)) || defaultLocale); const setState = state[1]; if (hydration && !defaultLocale) useEffect(() => { const locale = getClientLocale.call(t, path); if (locale) setState(locale); }, []); state[1] = (l) => { setClientLocale.call(t, l, path); setState(l); return l; }; t && useMemo(() => { const { settings } = t; if (settings.setLocale) { const { setLocale } = settings; settings.setLocale = (l) => (setState(l), setLocale(l)); } else settings.setLocale = state[1]; }, [t.settings]); state.setLocale = state[1]; state.locale = state[0]; state.toString = () => state[0]; return state; }