feat: create useLocale hook to get user locale
This commit is contained in:
parent
b09c12eda1
commit
81503ab7cd
1 changed files with 29 additions and 0 deletions
29
src/client/hooks/useLocale.ts
Normal file
29
src/client/hooks/useLocale.ts
Normal file
|
@ -0,0 +1,29 @@
|
|||
import { useRouter } from 'next/router';
|
||||
import { parseCookies, setCookie } from 'nookies';
|
||||
import { trpc } from '@/utils/trpc';
|
||||
import { Locale, getLocaleFromString } from '@/shared/internationalization/locales';
|
||||
|
||||
export const useLocale = () => {
|
||||
const router = useRouter();
|
||||
const cookies = parseCookies();
|
||||
const me = trpc.auth.me.useQuery();
|
||||
const changeUserLocale = trpc.auth.changeLocale.useMutation();
|
||||
const browserLocale = typeof window !== 'undefined' ? window.navigator.language : undefined;
|
||||
|
||||
const locale = me.data?.locale || cookies.locale || browserLocale || 'en';
|
||||
|
||||
const changeLocale = async (l: Locale) => {
|
||||
if (me.data) {
|
||||
await changeUserLocale.mutateAsync({ locale: l });
|
||||
}
|
||||
|
||||
setCookie(null, 'locale', l, {
|
||||
maxAge: 30 * 24 * 60 * 60,
|
||||
path: '/',
|
||||
});
|
||||
|
||||
router.reload();
|
||||
};
|
||||
|
||||
return { locale: getLocaleFromString(locale), changeLocale };
|
||||
};
|
Loading…
Add table
Reference in a new issue